TypeScript's 'infer' Keyword: Extracting Types from Wrapped Values

When you first come across 'Conditional Types' in TypeScript, there’s one keyword that suddenly starts appearing everywhere - 'infer'. And when people first see it, the reaction is usually - 'Wait… TypeScript can extract types now?' Yes. And that’s exactly what infer is about. In simple terms, 'infer' allows TypeScript to capture a type from inside another type and give it a name, so you can reuse it. It only works inside conditional types, and that’s important. Using this keyword, you are asking TypeScript - 'If this type matches a certain shape, can you pull out a part of it for me?' This is really powerful because in real code, we often work with wrapped types. Promises wrap values, Arrays wrap elements. Functions wrap return types, APIs wrap responses etc. And without 'infer', you’d have to manually describe every possible variation. With 'infer', you can extract the interesting part automatically. This is the reason TypeScript can unwrap Promise values, extract function return types, pull parameter types from functions, and power utility types like 'ReturnType', 'Awaited', and 'Parameters'. All of those are built on 'infer'. Another important thing to understand is that 'infer' doesn’t 'guess'. It only works when the surrounding conditional type matches. If the structure doesn’t match, the conditional type falls back to its alternative branch. Remember - 1. Conditional types decide which branch to take. 2. 'infer' lets you name a piece of the type inside that branch. #TypeScript #JavaScript #Programming #WebDevelopment #Coding

  • text

To view or add a comment, sign in

Explore content categories