typescript - 有没有办法在 typescript 定义中引用函数参数?

标签 typescript types

我有一个{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/

相关文章:

javascript - jest.doMock 和 JSON 导入模拟

javascript - ngFor 之后的 Angular 2 火灾事件

typescript - 为具有多个入口点的库导出声明

c++ - 虽然循环在输入方面表现得很奇怪

c# - 按类型名称获取 GUID

scala - 映射一个无形的 HList 的类型

javascript - 导出单个或多个类型

Angular 2 : What is the recommended access modifier for typescript properties and functions that will be accessed in the view

c - 这段代码中的不透明是什么?

c++ - 当我们对一个int进行运算时,结果是不是暂存在一个int中呢?