你能提取 Class 中所有方法的签名吗?
Can you Extract the Signature of all the Methods inside a Class?
假设我有这个 class:
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 ...
}
所有class方法return一个相似对象:{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>
然而这个 class 有数百行。有没有办法从 class 中的所有方法中提取所有可能的 return 值而无需手动执行?
我正在使用版本 "typescript":“3.7.2”
您可以使用映射类型遍历 class 的属性,使用条件类型来过滤方法并提取 return 类型。然后索引这个映射类型以获得映射类型中所有可能值的并集
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>
编辑
如果Actions
只包含函数,也可以利用ReturnType
的分布式特性得到Actions
中所有函数的return类型:
type AllActions = ReturnType<Actions[keyof Actions]>;
假设我有这个 class:
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 ...
}
所有class方法return一个相似对象:{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>
然而这个 class 有数百行。有没有办法从 class 中的所有方法中提取所有可能的 return 值而无需手动执行?
我正在使用版本 "typescript":“3.7.2”
您可以使用映射类型遍历 class 的属性,使用条件类型来过滤方法并提取 return 类型。然后索引这个映射类型以获得映射类型中所有可能值的并集
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>
编辑
如果Actions
只包含函数,也可以利用ReturnType
的分布式特性得到Actions
中所有函数的return类型:
type AllActions = ReturnType<Actions[keyof Actions]>;