TypeScript and dot-notation access to objects

前端 未结 5 417
半阙折子戏
半阙折子戏 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 17:00

    I personally prefer to specify types whenever I have the chance.

    Note, that you can only instantiate this variable with {} if you define the fields as optional with the ?: operator.

    let x: {foo?: string, bar?: string} = {};
    x.foo = 'foo';
    x.bar = 'bar';
    

    As others have said, if you plan to use this type multiple times, it's probably better to make an explicit class for it.

    PS: it's better to use let instead of var when programming in typescript. (e.g. the scope of a var declaration is a bit quirky, compared to a let which does what you expect it to do.)

提交回复
热议问题