I'm encountering difficulties when utilizing a generic type in combination with keyof
inside a Proxy()
:
The following example code is not functioning and indicates a lack of assignable types:
interface SomeDataStructure {
name?: string;
}
class DataWrapper<T extends SomeDataStructure> {
data: T;
constructor(data: T) {
this.data = data;
return new Proxy(this, {
get: (target: this, property: keyof T): any => {
return target.data[property];
}
});
}
}
The error message (on get
):
Type '(target: this, property: keyof T) => any' is not compatible with type '(target: this, p:
string | symbol, receiver: any) => any'.
Parameters 'property' and 'p' have incompatible types.
Type 'string | symbol' cannot be assigned to type 'keyof T'.
Type 'string' cannot be assigned to type 'keyof T'.
Type 'string' cannot be assigned to type '"name"'.ts(2322)
If I directly use keyof SomeDataStructure
, instead of keyof T
, the error vanishes and everything seems to work fine:
interface SomeDataStructure {
name?: string;
}
class DataWrapper<T extends SomeDataStructure> {
data: T;
constructor(data: T) {
this.data = data;
return new Proxy(this, {
get: (target: this, property: keyof SomeDataStructure): any => {
return target.data[property];
}
});
}
}
Alternatively, specifying
keyof T extends SomeDataStructure
(similar to the class definition) also resolves the issue. The usage of keyof T
in general for class methods outside of the Proxy()
functions smoothly.
It appears that the type of T
gets lost when wrapping things within new Proxy()
. How can I maintain the reference to T
for keyof T
in this scenario?