Obi Fortune

Understanding the infer keyword

Saturday 6 January 2024

main image for Understanding the infer keyword

ELI5 - Explaining infer

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;

take this type
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

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