Narrowing a return type from a generic, discriminated union in TypeScript

前端 未结 5 2072
执念已碎
执念已碎 2020-12-09 03:09

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

5条回答
  •  悲哀的现实
    2020-12-09 03:35

    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

提交回复
热议问题