Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does [keyof T] mean after the closing brace in type definition? [duplicate]

Tags:

typescript

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?

like image 768
Dmitri Avatar asked Sep 06 '25 15:09

Dmitri


1 Answers

That's called a "lookup type".

  1. keyof X returns all keys of a type

  2. 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 as 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".

like image 68
Sergiu Paraschiv Avatar answered Sep 11 '25 01:09

Sergiu Paraschiv