Typescript: What's the difference between an optional field and a union with undefined?

前端 未结 1 1808
名媛妹妹
名媛妹妹 2020-12-11 14:59

I want to define an interface with optional fields. I thought the following were synonymous.

(A):

interface State {
  userDetails: unde         


        
相关标签:
1条回答
  • 2020-12-11 15:33

    Even at runtime there is a difference between a key with an undefined value and a key that doesn't exist. That TypeScript allows differentiating is not surprising.

    Try this:

    Object.keys({a: undefined});
    

    If leaving a out and setting it's value to be undefined were the same thing then we'd expect the above to return an empty array, but in fact it returns

    [ 'a' ]
    
    0 讨论(0)
提交回复
热议问题