我是JavaScript和typecipt的新手。下面是我的代码:
let myObj:Object = { foo: 'bar' };
let strVar:string = myObj.foo; // then it throw an error that "property foo does not exist on type 'Object'"
那么,为什么我不能访问对象的属性?
这是正确的,因为foo
并非Object
类型的属性。您需要进行以下更改:
let myObj:{ foo: string } = { foo: 'bar' };
let strVar:string = myObj.foo;
您还可以声明一个接口:
interface MyObject {
foo: string;
}
let myObj: MyObject = { foo: "bar" };
let strVar:string = myObj.foo;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句