Member-only story

The NoInfer Utility Type: a new awesome TypeScript feature

an exciting feature coming soon to TypeScript 5.4

Jose Granja
3 min readMar 2, 2024
Image by Author

First, let’s do a quick recap on what infer is and how to use it.

The infer keyword in TypeScript acts as a sophisticated mechanism for deducing types from existing types or expressions. It empowers developers to precisely extract and work with specific types within larger, more complex type structures. This functionality is particularly valuable in scenarios where understanding and manipulating nested or conditional types is essential for robust type inference and accurate type checking.

For example, consider the following code:

// type to extra the type of the x property
type ExtractX<T> = T extends { x: infer U } ? U : never;

type Result1 = ExtractX<{x: string}>; // Result1 is string
type Result2 = ExtractX<{x: 'foo'}>; // Result2 is foo
type Result3 = ExtractX<{j: string}>; // Result3 is never

Here, we are defining a generic type called ExtractX, which takes a type parameter T. The type parameter is then used in a conditional type that checks whether the type has a property called x. If it does, we extract the type of the x property using the infer keyword and assign it to a new type U. Otherwise, it does return the never type.

--

--

Jose Granja
Jose Granja

Written by Jose Granja

Top Writer @Medium | 1M+ Views | Lead FE @Lingoda | I write weekly about web-development topics 📰 Support me at https://dioxmio.medium.com/membership 🙇

No responses yet