【问题标题】:Create record from interface with return type as property type from original interface从接口创建记录,返回类型为原始接口的属性类型
【发布时间】:2020-01-13 04:03:50
【问题描述】:

我有一个类似的界面

inteface A {
  a: number
}

我想创建一个对象的类型,其中键作为 A 的键,值作为返回键类型的函数

例子

const obj = {
  a: () => 4
}

这里应该是obj 的类型,应该是采用A 接口的泛型

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    您可以为此使用映射类型:

    type Functionify<T> = { [K in keyof T]: () => T[K] }
    

    它遍历T 类型中的所有键(属性)并将它们映射到返回原始类型T[K] 的函数。

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 2020-09-04
      相关资源
      最近更新 更多