TypeScript and dot-notation access to objects

前端 未结 5 405
半阙折子戏
半阙折子戏 2020-12-09 16:11

If TypeScript is a strict superset of JavaScript, why is dot notation on an arbitrary object erroneous? I have JS code that I want to convert over to TS for better type safe

5条回答
  •  醉梦人生
    2020-12-09 16:54

    mwilson got there before I could! ;)

    In the code above, Typescript is unable to determine that the object x exposes a property called bar so cannot resolve it when displaying Intellisense.

    Instead, add foo, bar, etc. as properties of the object itself:

    var x = {
        foo: "FOO",
        bar: "BAR"
    };
    

    Then, when using the Typescript Playground, you'll be see the Intellisense work as expected:

    enter image description here

    HTH

提交回复
热议问题