user11224591
user11224591

Reputation:

why I cannot access Object's properties?

I'm new a newbie to JavaScript and typescipt. Below is my code:

let myObj:Object = { foo: 'bar' };
let strVar:string = myObj.foo; // then it throw an error that "property foo does not exist on type 'Object'"

So why I cannot access Object's properties?

Upvotes: 1

Views: 1264

Answers (1)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

That is true as the foo is not a property of the Object type. You need make the following change:

let myObj:{ foo: string } = { foo: 'bar' };
let strVar:string = myObj.foo;

You can also declare an interface:

interface MyObject {
    foo: string;
}

let myObj: MyObject = { foo: "bar" };
let strVar:string = myObj.foo;

Upvotes: 4

Related Questions