TypeScript and dot-notation access to objects

前端 未结 5 420
半阙折子戏
半阙折子戏 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条回答
  •  Happy的楠姐
    2020-12-09 17:02

    x does not hold any property named bar so you need create it within the object:

    function foobar() {
        var x = {
    
            foo: 'foo',
            bar: 'bar'
        }
    
        return x;
    }
    
    alert(foobar().bar); //returns bar
    

提交回复
热议问题