TypeScript 5.4 新特性详解
TypeScript 5.4 版本带来了哪些新特性?本文带你快速了解重点更新
TypeScript 5.4 新特性详解
TypeScript 5.4 正式发布!本文为你梳理最值得关注的新特性。
1. NoInfer 工具类型
新增的 NoInfer 工具类型可以阻止 TypeScript 自动推断类型:
function createState<T>(initial: NoInfer<T>) {
let current = initial;
return {
get: () => current,
set: (value: T) => { current = value; }
};
}
// 现在 initial 不会被自动推断为 string
const state = createState("hello");
2. 改进的闭包类型推断
TypeScript 5.4 改进了闭包中的类型推断:
function makeCounter() {
let count = 0;
return {
increment: () => { count++; return count; },
getCount: () => count
};
}
现在 TypeScript 能更准确地推断闭包中变量的类型。
3. 保留 const 推断
在特定场景下,TypeScript 现在会保留 const 的语义:
const config = {
port: 3000,
host: "localhost"
} as const;
// 类型更精确:{ readonly port: 3000; readonly host: "localhost" }
4. 性能提升
5.4 版本还带来了显著的构建性能提升,特别是在大型项目中。
这些新特性让 TypeScript 更加强大和灵活。快去升级体验吧!