I've been diving into TypeScript and experimenting with mapped types to create a function that restricts users from extracting values off an object unless the keys exist. Take a look at the code below:
const obj = {
a: 1,
b: 2,
c: 3
}
function getValues<T, K extends keyof T>(obj: T, keys: K[]) {
return keys.map(key => obj[key])
}
getValues(obj, ['a', 'b'])
In this implementation, I specified two type parameters T
and K
. The TypeScript compiler automatically infers these types when the function is called without explicit type declarations.
Now, my curiosity has led me to wonder how I can explicitly pass types to the function to understand the type inference better. I attempted the following:
getValues<typeof obj, string[] extends keyof typeof obj>(obj, ['a'])
However, the compiler throws a parsing error stating Parsing error: '?' expected
. It seems my attempt didn't yield the intended outcome.