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

前端 未结 3 1215
南笙
南笙 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条回答
  •  -上瘾入骨i
    2021-02-20 02:30

    typeof doesn't do this. It always return "string", "number", "boolean", "object", "function", or "undefined".

    You can test for object properties with a test like if(thing.a !== undefined) { or if(thing.hasOwnProperty('a')) {.

    Note that you could make an object that had both a string a and a string b, so be aware of that possibility.

提交回复
热议问题