Looking at the Typescript documentation at this URL https://www.typescriptlang.org/docs/handbook/advanced-types.html
type FunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends Function ? K : never;
}[keyof T];
Can someone explain to me what this [keyof T] after the closing brace mean? Is there any documentation for this syntax?
That's called a "lookup type".
keyof X
returns all keys of a type
if
interface a {
foo: never
bar: string
baz: number
}
then type not_here = a['foo']
will be never
but lookup types also support passing keyof Something
in, so
a[keyof a]
would be the union of all types of a
s keys/properties, which is never | string | number
. Though never
has no meaning in there so TS automatically ignores it, resulting in string | number
.
(you can of course do a[keyof b]
, there's no restriction here)
I find that the best way to figure out complex types like this one is to decompose them in steps like I did here:
interface test {
a: string
b: () => void
c: () => void
}
type T_A<T> = {
[K in keyof T]: T[K]
};
type T_B<T> = {
[K in keyof T]: T[K] extends Function ? K : never;
};
type T_C<T> = {
[K in keyof T]: T[K] extends Function ? K : never;
}[keyof T];
type a = T_A<test>
type b = T_B<test>
type c = T_C<test>
With this you can see the individual steps taken to obtain the desired result, which is "the union of keys which are of type Function".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With