Why can I avoid excess property check in typescript just by passing a reference to an object to a function rather than the object in its literal form?

前端 未结 1 1921
独厮守ぢ
独厮守ぢ 2020-12-11 07:36

Have a look at this example typescript code

function printLabel(labelledObj: { label: string }) {
    console.log(labelledObj.label);
}

printLabel({ size: 1         


        
相关标签:
1条回答
  • 2020-12-11 07:51

    It's by design. In short, Typescript creators made it this way because they know Javascript is a very dynamic language with many such use cases.

    You should read this carefully: https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks (however I bet the question arised from reading it).

    Object literals get special treatment

    Their logic might be like this: if you have a variable, then it may come from some third party and there is not much you can do with it. On the other hand, if you pass object literal, then you are responsible for its correct type.

    0 讨论(0)
提交回复
热议问题