I've been struggling with this issue for quite some time,
function processEntity<
T extends Record<string, unknown>,
U extends keyof T = keyof T,
V extends Pick<T, U> = Pick<T, U>
>(arg: {keys: Array<U>; resolver: (doc: V) => void}) {
arg.resolver(...)
}
type Cat = {
name: string
age: number
}
processEntity<Cat>({
keys: ['name'],
resolver: (doc) => {
// doc.name should exist
// doc.age should be undefined
},
})
As shown above, there is a function called processEntity
that takes an object as an argument.
My goal is to have the
type of the argument in arg.resolver
depend on the type of arg.keys
. For example, if I pass ['name']
to the keys:
field, then doc.age
should not be accessible because 'age'
was missing in the keys
field.
I have looked at some related questions listed below but they have not been helpful, so please provide assistance :pray:
- How to define a function's argument type dependent on string argument in Typescript?
- Typescript make one parameter type depend on the other parameter
- Declaring dependent argument types for optional arguments with conditional types
- Typescript. Correctly typing function parameter that depends on property in the same object literal