Check if variable is a specific interface type in a typescript union

前端 未结 3 1227
南笙
南笙 2021-02-20 02:10

Is it possible to create a typeguard, or something else that accomplishes the same purpose, to check if a variable is a specific interface type in a typescript union?

         


        
3条回答
  •  北荒
    北荒 (楼主)
    2021-02-20 02:20

    In TypeScript 2 you can use Discriminated Unions like this:

    interface Foo {
        kind: "foo";
        a:string;
    }
    interface Bar {
        kind: "bar";
        b:string;
    }
    type FooBar = Foo | Bar;
    let thing: FooBar;
    

    and then test object using if (thing.kind === "foo").

    If you only have 2 fields like in the example I would probably go with combined interface as @ryan-cavanaugh mentioned and make both properties optional:

    interface FooBar {
        a?: string;
        b?: string
    }
    

    Note that in original example testing the object using if (thing.a !== undefined) produces error Property 'a' does not exist on type 'Foo | Bar'.

    And testing it using if (thing.hasOwnProperty('a')) doesn't narrow type to Foo inside the if statement.

    @ryan-cavanaugh is there a better way in TypesScript 2.0 or 2.1?

提交回复
热议问题