Search code examples
typescriptobject-literal

TypeScript error when accessing property of object literal


I'm a beginner in TypeScript. I had a bit problem when accessing data of an Object.

let content:Array<string> = ["I", "am", "a", "beginner"]
let data:Object = {a: "foo", b: content}
console.log(data.a);
console.log(data['b']);
console.log(data.b);

This code will have an error in line 5. (no error in JavaScript) Please, explain it to me. Thanks for any help.


Solution

  • Just remove the explicit declaration of data to be of Object so that TypeScript will infer the type, i.e. change it to something like this

    let content:Array<string> = ["I", "am", "a", "beginner"]
    let data = {a: "foo", b: content}
    console.log(data.a);
    console.log(data['b']);
    console.log(data.b);
    

    The reason for your error in your initial code is because you are telling the TypeScript compiler that data is of type Object or any derived class from that - as the type Object has no properties a or b this results in an error.

    Please note that removing the explicit type annotation is not the same as using any as suggested by AD.Net as in this case TypeScript still has all the type information available - just inferred (see the screenshot of Visual Studio Code), whereas by using any you are telling the TypeScript compiler that the variable could refer to anything which results in no type checking.

    enter image description here