首页 > 解决方案 > 将打字稿类型从函数提取到对象

问题描述

尝试从给定的函数类型生成类型。我想直接从函数中获取返回类型并映射到下面显示的对象的键。我ReturnType试过了,但它不接受这种reducers结构。

type A = { a: string } 
type B = {  b: string }
type Reducers = {
  aA: (a) => A,
  bB:(b) => B,
}

const reducers: Reducers = {
  aA: (a) => { a },
  bB: (b) => {b },
}

如何获得商店状态

namespace Store {  // I will provide this
  type Project = { // here is where I need to generated types based on reducer function like`type Project = ....`
     aA: A,
     bB: B,
  } 
}

标签: typescript

解决方案


我不确定你想要什么,但这里是如何ReturnType映射类型中使用:

type Project = {
  [K in keyof Reducers]: ReturnType<Reducers[K]>
}

……或更通用的版本:

interface ReducerDict {
  [key: string]: (...args: any[]) => any
}

type Project<T extends ReducerDict> = {
  [K in keyof T]: ReturnType<T[K]>
}

推荐阅读