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

前端 未结 3 1210
南笙
南笙 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:22

    Since Typescript 1.6 you can use user-defined type guards:

    let isFoo = (object: Foo| Bar): object is Foo => {
        return "a" in object;
    }
    

    See https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards and https://github.com/microsoft/TypeScript/issues/10485

提交回复
热议问题