TypeScript 5.4 Overview
TypeScript 5.4 was released in March 2024, adding features that improve developer experience, such as improved type inference and NoInfer type.
NoInfer Utility Type
NoInfer<T> is a utility type that prevents type parameter inference at specific positions.
Problematic Code (Before 5.4)
function createStreetLight<T extends string>(
colors: T[],
defaultColor: T
) {
// ...
}
// 'blue' is also inferred
createStreetLight(['red', 'yellow', 'green'], 'blue');
// → T = 'red' | 'yellow' | 'green' | 'blue'
Solution Using NoInfer
function createStreetLight<T extends string>(
colors: T[],
defaultColor: NoInfer<T>
) {
// ...
}
// Error! 'blue' is not included in 'red' | 'yellow' | 'green'
createStreetLight(['red', 'yellow', 'green'], 'blue');
Use Case: Useful when you want to infer types from only some arguments in a generic function.
Improved Type Narrowing in Closures
Type guards within closures have become smarter.
function getUrls(url: string | URL, names: string[]) {
if (typeof url === 'string') {
// Before: url remains string | URL
// 5.4: url is narrowed to string
return names.map(name => {
return url + '/' + name; // OK!
});
}
return names.map(name => url.href + '/' + name);
}
Object.groupBy and Map.groupBy Support
Type definitions for new grouping methods have been added.
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 25 }
];
// Object.groupBy
const byAge = Object.groupBy(users, user => user.age);
// { 25: [...], 30: [...] }
// Map.groupBy
const byAgeMap = Map.groupBy(users, user => user.age);
// Map { 25 => [...], 30 => [...] }
Import Attributes
You can specify attributes when importing modules such as JSON.
import config from './config.json' with { type: 'json' };
// Dynamic import
const data = await import('./data.json', {
with: { type: 'json' }
});
Other Improvements
- require() type support improvement: Better ESM and CJS interoperability
- —moduleResolution bundler improvement: More accurate resolution in bundler environments
- Editor support improvements: Improved rename and import organization
Summary
TypeScript 5.4 enables more accurate and intentional typing with NoInfer type and closure type inference improvements. Object.groupBy type support is also a useful improvement for practical use.
← Back to list