[英]How to access object by dot notation or bracket notation in Typescript?
I'm new to typescript.我是 typescript 的新手。
I created a simple class with a getter.我用吸气剂创建了一个简单的 class。
But it's not accessible to a child value of the getter object.但是 getter object 的子值无法访问它。
What's wrong with my codes?我的代码有什么问题?
class TestObjectWrapper {
private _obj: Object;
constructor(_obj: Object) {
this._obj = { ..._obj };
}
get obj(): Object {
return { ...this._obj };
}
}
const testObj1 = { a: '01', b: '02' };
const testInstance = new TestObjectWrapper(testObj1);
console.log(testObj1); // {"a": "01", "b":"02"}
console.log(testObj1.a); // "01"
console.log(typeof(testInstance.obj)); // "object"
console.log(testInstance.obj); // {"a": "01", "b":"02"}
Why are the codes below inaccessible?为什么下面的代码无法访问?
I expected to get "01".我希望得到“01”。
console.log(testInstance.obj.a);
//Property 'a' does not exist on type 'Object'.
console.log(testInstance.obj["a"]);
// Element implicitly has an 'any' type because expression of type '"a"' can't be used to index type 'Object'.
Property 'a' does not exist on type 'Object'.
The Object
type used in TestObjectWrapper
only has properties that all objects share, and a
isn't one of them. TestObjectWrapper
中使用的Object
类型仅具有所有对象共享的属性,而a
不是其中之一。
You can fix this by inferring a generic type T
in TestObjectWrapper
:您可以通过在
TestObjectWrapper
中推断泛型类型T
来解决此问题:
class TestObjectWrapper<T> {
private _obj: T;
constructor(_obj: T) {
this._obj = { ..._obj };
}
get obj(): T {
return { ...this._obj };
}
}
It would be good if you type your private property and getter correctly and then accessing it.如果您正确键入您的私有财产和吸气剂然后访问它,那将是一件好事。 You can change your code like below and this way you can remove this error.
您可以像下面这样更改您的代码,这样您就可以消除此错误。
interface MyObj {
a: string;
b: string
}
class TestObjectWrapper {
private _obj: MyObj;
constructor(_obj: MyObj ) {
this._obj = { ..._obj };
}
get obj(): MyObj {
return { ...this._obj };
}
}
const testObj1 = { a: '01', b: '02' };
const testInstance = new TestObjectWrapper(testObj1);
let gettedObj = testInstance.obj;
console.log(gettedObj.a);
console.log(testInstance.obj["a"]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.