【问题标题】:Can you Extract the Signature of all the Methods inside a Class?你能提取一个类中所有方法的签名吗?
【发布时间】:2020-03-31 20:22:53
【问题描述】:

假设我有这个课程:

class Actions {
  static FooAction = 'foo' as const;
  someAction1() {
    return {
     type: Actions.FooAction,
     payload: {a: 1, b:2}
  }}

  static BarAction = 'bar' as  const;
  someAction2() {
    return {
     type: Actions.BarAction,
     payload: {c: 3, e:2}
  }}
  ... keeps going ...
}

所有类方法都返回一个类似的对象:{type: string, payload: Record<string, number>}

但是我想更严格一些。我希望它是

type ReturnedActions = 
| { type: 'foo', {a: string, b:string} } 
| { type: 'bar', {c: string, e:string} } 
...

因为我可以使用开关按类型过滤:

declare var a: ReturnedActions 

switch (a.type) {
  case 'foo': 
    payload.c // error
}

我知道我能做到

var actions = new Actions(); 
type = ReturnType<typeof actions.someAction1> |  ReturnType<typeof actions.someAction2>

但是这个类有数百行。有没有办法从类中的所有方法中提取所有可能的返回值而无需手动执行?

我正在使用版本“typescript”:“3.7.2”

【问题讨论】:

    标签: typescript typescript3.0


    【解决方案1】:

    您可以使用映射类型来遍历类的属性,并使用条件类型来过滤方法并提取返回类型。然后,您索引此映射类型以获取映射类型中所有可能值的并集

    type ReturnedActions<T> = {
        [P in keyof T]: T[P] extends (...a: any) => infer R ? {
            type: P,
            payload: R
        } : never
    }[keyof T]
    
    type AllActions = ReturnedActions<Actions>
    
    

    Playground link

    编辑 如果Actions只包含函数,还可以利用ReturnType的分配性质来获取Actions中所有函数的返回类型:

    type AllActions = ReturnType<Actions[keyof Actions]>;
    

    【讨论】:

    • 您也可以使用ReturnType 执行此操作,而不是声明ReturnedActionstype AllActions = ReturnType&lt;Actions[keyof Actions]&gt;;如果您想将其添加到您的答案中
    • @lonewarrior556 很公平,这也是可能的,但只有当Actions 的所有公共成员都是函数时才有效。我不一定清楚是这种情况
    • 啊,这个信息也有帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多