I have a class method which accepts a single argument as a string and returns an object which has the matching type property. This method is used to narrow a di
As of TypeScript 2.8, you can accomplish this via conditional types.
// Narrows a Union type base on N
// e.g. NarrowAction would produce ExampleAction
type NarrowAction = T extends { type: N } ? T : never;
interface Action {
type: string;
}
interface ExampleAction extends Action {
type: 'Example';
example: true;
}
interface AnotherAction extends Action {
type: 'Another';
another: true;
}
type MyActions =
| ExampleAction
| AnotherAction;
declare class Example {
doSomething(key: K): NarrowAction
}
const items = new Example();
// Inferred ExampleAction works
const result1 = items.doSomething('Example');
NOTE: Credit to @jcalz for the idea of the NarrowAction type from this answer https://stackoverflow.com/a/50125960/20489