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'.
CodePudding user response:
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 };
}
}
CodePudding user response:
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"]);