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

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

    Unfortunately, you cannot achieve this behavior using union type (ie type MyActions = ExampleAction | AnotherAction;).

    If we have a value that has a union type, we can only access members that are common to all types in the union.

    However, your solution is great. You just have to use this way to define the type you need.

    const result2 = items.doSomething('Example');
    

    Although you don't like it, it seems pretty legit way to do what you want.

提交回复
热议问题