While reviewing the documentation on Advanced Types in Typescript, I came across an interesting concept known as the Index Query Operator. The documentation can be found here: https://www.typescriptlang.org/docs/handbook/advanced-types.html. One example provided was the following code snippet:
function pluck<T, K extends keyof T>(o: T, names: K[]): T[K][] {
return names.map(n => o[n]);
}
It's clear to me how keyof
generates a union of all known public property names on object T
. However, I'm unsure about the specific role of the extends
keyword. I understand that it enforces that K
must be a valid property of T
, but I'm curious as to why extends
is used and if there are other alternatives. Additionally, I'm wondering if it's possible to extend unions in Typescript, or if this is a concept specific to generics.
Any insights on this would be greatly appreciated. Thank you.