【发布时间】: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”
【问题讨论】: