Hero

Understanding the infer keyword

a few seconds read

ELI5 - Explaining infer


Take this type

MyAwaited.ts
type MyAwaited<T> = T extends Promise<infer R>
    ? R extends Promise<any>
    ? MyAwaited<R>
    : R
    : T extends { then: (onfulfilled: (args: infer B) => any) => any }
    ? B
    : never;

we first check if the type passed T is a type of Promise<infer R> (assume that R is any value)
if yes then we can say return the value in R (infer will essentially capture the value)
if not then we make the next check (for the .then()) and we do the same thing
if the two fail then we return never


----


btw a fun and actually very useful thing about infer is that you can add extends to make sure that you only catch specific types

i.e if you do

FirstString.ts
type First<T extends any[]> = T extends [infer First extends string, ...infer Next] ? First : never;

it'll only capture First if First happens to be a string this means the extends will fail and you'll get never