Issue
I'm new to typescript.
I created a simple class with a getter.
But it's not accessible to a child value of the 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".
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'.
Solution
The Object
type used in TestObjectWrapper
only has properties that all objects share, and a
isn't one of them.
You can fix this by inferring a generic type T
in TestObjectWrapper
:
class TestObjectWrapper<T> {
private _obj: T;
constructor(_obj: T) {
this._obj = { ..._obj };
}
get obj(): T {
return { ...this._obj };
}
}
Answered By - Nick McCurdy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.