How does the `infer` keyword work in TypeScript?
13 August 2023 (Updated 14 August 2023)
On this page
In a nutshell
The infer
keyword in TypeScript lets you capture and extract a type in the context of conditional type expressions. infer
only works when used inside a conditional type expression.
Here’s an example use:
type ExtractReturnType<T extends (...args: any[]) => any> = T extends (
...args: any[]
) => infer R
? R
: never
function addNums(a: number, b: number) {
return a + b
}
function getGreeting() {
return "Hi there"
}
type AddNumsReturnType = ExtractReturnType<typeof addNums>
type GetGreetingsReturnType = ExtractReturnType<typeof getGreeting>
See this example in the TypeScript playground.
Sources / relevant links
Tagged:
TypeScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment