我有一个{string: Function}
映射a
:
const a: A = {
foo: (x: string) => 8,
bar: (y: number, z: boolean) => 6,
}
然后我将其转换为每个映射函数都有不同类型的返回值:
const b: B = {
foo: (x: string) => (8).toString(),
bar: (y: number, z: boolean) => (6).toString(),
}
在 TypeScript 中,有什么方法可以将类型 B
描述为派生自 A
,在我的梦想世界中,我希望能够做到:
type A = {
foo: (string) => number
bar: (number, boolean) => number
}
type B = {
[K in keyof A]: (E in argsof A[K]) => string
}
最佳答案
在 Typescript 中梦想成真 :)
您可以使用 conditional types 在 Typescript 3.0 中实现此目的和 Tuples in rest parameters and spread expressions :
type A = {
foo: (s: string) => number
bar: (n: number, b: boolean) => number
}
type ArgumentTypes<T extends (...a: any[]) => any> = T extends (...a: infer A) => any ? A : [];
type B = {
[K in keyof A]: (...a:ArgumentTypes<A[K]>) => string
}
let b: B;
b.foo("") // works
b.foo(1) // error
关于typescript - 有没有办法在 typescript 定义中引用函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53334993/