Looking to create a JavaScript Proxy
that enables access to arbitrary properties. For example, an object that assigns each property its own name:
const proxy = new Proxy({}, {
get(target, property) {
return prop;
}
});
proxy.foo // results in "foo"
// Property 'foo' does not exist on type '{}'.ts(2339)
I understand that TypeScript may not automatically recognize the existence of proxy.foo
, but I am seeking a way to specify a type so that it knows the property exists and also the value type depends on the specific property name.
The mapped type below prevents TypeScript from flagging the property as non-existent, however it infers the type as string
instead of the more precise "foo"
:
const proxy = new Proxy<{ [T in string]: T }>({}, {
get(target, prop) {
return prop;
}
});
proxy.foo // inferred as `string` instead of `"foo"`
I have also attempted using { readonly [T in string]: T }
.
Interestingly,
({} as { [T in "foo" | "bar"]: T }).foo
will be recognized as `"foo"`, however, I cannot list out all potential keys.
Is there a method to make TypeScript utilize the exact key within the value's type in a mapped type, or another technique to precisely type a Proxy
with dynamic properties?