有没有办法在typescript定义中引用函数参数?
我有一个有没有办法在typescript定义中引用函数参数?,typescript,types,Typescript,Types,我有一个{string:Function}mapa: 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).toSt
{string:Function}
mapa
:
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 3.0中实现这一点:
A型={
foo:(s:string)=>数字
条:(n:number,b:boolean)=>number
}
类型参数类型任意>=T扩展(…a:推断a)=>任意?A:[];
B类={
[K in keyof A]:(…A:ArgumentTypes)=>string
}
让b:b;
b、 富(“”//作品
b、 foo(1)//错误
从Typescript 3.1开始,您可以使用内置的参数来实现这一点:
type B = {
[K in keyof A]: (...a: Parameters<A[K]>) => string
}
类型B={
[K in keyof A]:(…A:参数,但类似的条件类型是,如ReturnType
,您可以在中看到它们
考虑到这一点,我们可以更进一步,使用ReturnType
将B与转换函数的返回类型联系起来:
const transformingFunction:(n:number)=>string=(n:number)=>n.toString();
B类={
[K in keyof A]:(…A:Parameters)=>ReturnType
}
现在,如果我们想改变转换函数的返回类型,可以在一个地方完成,也就是在函数本身上,而不破坏B的签名
type B = {
[K in keyof A]: (...a: Parameters<A[K]>) => string
}
const transformingFunction: (n: number) => string = (n: number) => n.toString();
type B = {
[K in keyof A]: (...a: Parameters<A[K]>) => ReturnType<typeof transformingFunction>
}