2

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.

1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

You might mention that the reason the initial assignment works is that TS ignores extra properties.
#torazaburo I am starting learning Typescript. I had a problem with my data in my project. But now I understand.
That's a good point about not using any, I haven't used TS in a while :(
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.