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

前端 未结 5 2075
执念已碎
执念已碎 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:38

    A little more verbose on the setup but we can achieve your desired API with type lookups:

    interface Action {
      type: string;
    }
    
    interface Actions {
      [key: string]: Action;
    }
    
    interface ExampleAction extends Action {
      type: 'Example';
      example: true;
    }
    
    interface AnotherAction extends Action {
      type: 'Another';
      another: true;
    }
    
    type MyActions = {
      Another: AnotherAction;
      Example: ExampleAction;
    };
    
    declare class Example {
      doSomething(key: K): T[K];
    }
    
    const items = new Example();
    
    const result1 = items.doSomething('Example');
    
    console.log(result1.example);
    

提交回复
热议问题