我有一张{string: Function}地图a:
const a: A = {
foo: (x: string) => 8,
bar: (y: number, z: boolean) => 6,
}
Run Code Online (Sandbox Code Playgroud)
然后我转换它,使每个映射函数具有不同类型的返回值:
const b: B = {
foo: (x: string) => (8).toString(),
bar: (y: number, z: boolean) => (6).toString(),
}
Run Code Online (Sandbox Code Playgroud)
在TypeScript中,有没有办法将类型描述B为派生自A,在我的梦想世界中,我希望能够做到:
type A = {
foo: (string) => number
bar: (number, boolean) => number
}
type B = {
[K in keyof A]: (E in argsof A[K]) => string
}
Run Code Online (Sandbox Code Playgroud)
在Typescript :)梦想成真
你可以在Typescript 3.0中使用条件类型和休息参数和扩展表达式中的元组来实现这一点:
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
Run Code Online (Sandbox Code Playgroud)