Let's consider a scenario where we have a class defined as follows:
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}
}}
... and so on ...
}
All the methods within this class return an object with a similar structure:
{type: string, payload: Record<string, number>}
However, to enforce stricter typing, we want it to be:
type ReturnedActions =
| { type: 'foo', {a: string, b:string} }
| { type: 'bar', {c: string, e:string} }
...
This allows us to use a switch statement to filter by type:
declare var a: ReturnedActions
switch (a.type) {
case 'foo':
payload.c // error
}
We are aware that we can manually define the types using ReturnType for each method:
var actions = new Actions();
type = ReturnType<typeof actions.someAction1> | ReturnType<typeof actions.someAction2>
But handling this manually in a lengthy class may not be ideal. Is there a way to automatically extract all possible return values from all methods in the class without having to do it manually?
The TypeScript version being used is "3.7.2"