1

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?

2
  • This is not a javascript error. Error is caused by typescript. This error will be eliminated when you properly set the type of myObj. Refer Fullstack Guy's answer. Commented Dec 3, 2020 at 5:00
  • You can just omit the type to let the compiler infer. Commented Dec 3, 2020 at 5:01

1 Answer 1

4

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;
Sign up to request clarification or add additional context in comments.

Comments