Vien Nguyen
Vien Nguyen

Reputation: 385

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.

Upvotes: 2

Views: 2681

Answers (2)

DAXaholic
DAXaholic

Reputation: 35358

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

Upvotes: 2

AD.Net
AD.Net

Reputation: 13399

You can assign data:any, at least you will not get any error. If you want intellisense, you'll need to create a type/interface for data, e.g.

interface myData{
    a:string;
    b:Array<String>
}
data:myData

then you can have intellisense.

Upvotes: 0

Related Questions