我有一个 Node JS 函数,它的一个参数是一个带有键的对象,而值是解析为底层值的函数。
我们刚刚切换到 TS,我不知道如何定义参数的 key:value 类型,而且我不知道如何定义 function
作为值类型?
TS 函数如下所示...
const myJSFunction = o => input => ...
其中 o
是 string:function
对象。然后input
被传递到o
的每个函数values
中。
所以我正在考虑有一些类似的签名......
// define the generic <R> function as <U => any>
// define the generic <T> as an object of { string : R }
const myTSFunction = (o: T) => (input: U) => ...
或者什么?我在这里紧紧捕获救命稻草,因为我对 Typescript 还不够了解,不知道泛型的可能性。
谢谢
最佳答案
像这样的事情怎么样:
// We define what the type o is
// key: string means "any key should ..."
interface Obj<T> {
[key: string]: (input: T) => void,
};
// We instantiate an object for the test
const o: Obj<string> = {
a: (input) => { },
b: (input) => { },
};
// We define the function to work with any type of value of obj
// and call it for the test
function myTSFunction<T>(obj: Obj<T>, val: T): void {
obj[0](val);
}
关于node.js - 使用字符串键和函数值定义对象的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58237229/