To ensure that only existing keys are accessed on a specific object, I have implemented the following code:
function prop<O, K extends keyof O>(key: K, obj: O) {
return obj[key];
}
This validation method functions correctly when utilized in the following manner:
const obj = { foo: 'bar' };
prop('foo', obj); // valid
prop('bar', obj); // invalid
However, my goal is to restructure the code so that it functions like this instead:
const obj = { foo: 'bar' };
prop('foo')(obj); // should be allowed
prop('bar')(obj); // should trigger an error
Initially, I attempted to adjust the function as follows:
function prop<O, K extends keyof O>(key: K) {
return function inner(obj: O) {
return obj[key];
}
}
Unfortunately, this approach did not work and led to the following error:
Argument of type '"foo"' is not assignable to the parameter of type 'never'.
The reasoning behind this error makes sense to me as the object is not accessible during key validation.
As a result, my aim is to switch the validation logic from "verify that the key exists in the object" to "confirm that the object contains the key" immediately after the object is passed into the second function. If the key is not found, a type validation error should occur with no other restrictions at that specific point.
While it seems achievable using TypeScript, I am yet to discover a method to accomplish this with a fully dynamic key and object, where the only requirement for the object is the presence of the specified key.