TS 5.2 ~ 5.4 新特性
约 381 字大约 1 分钟
布欧-Lewyon
2026-05-16
首页 › TypeScript › TS 5.x 新特性 › TS 5.2 ~ 5.4
TS 5.2
using 声明(显式资源管理)
// 实现了 Disposable 接口的对象可自动释放资源
class FileHandler implements Disposable {
constructor(private path: string) {
console.log(`打开文件: ${path}`);
}
[Symbol.dispose]() {
console.log(`关闭文件: ${this.path}`);
}
}
function process() {
using file = new FileHandler('data.txt');
// ... 使用文件 ...
// 作用域结束时自动调用 file[Symbol.dispose]()
}
// await using(异步资源)
class DBConnection implements AsyncDisposable {
async [Symbol.asyncDispose]() {
await this.close();
}
private async close() { /* ... */ }
}装饰器元数据
// 装饰器可以获取和设置元数据
const metaKey = Symbol('meta');
function setMeta(value: string) {
return (target: any, context: ClassMethodDecoratorContext) => {
context.metadata[metaKey] = value;
};
}
@setMeta('service')
class MyService {}TS 5.3
importAttributes
// 导入模块时携带属性(如 JSON 类型断言)
import data from './config.json' with { type: 'json' as const };satisfies 完善
type Pair = [string, string];
type Config = Record<string, string>;
// satisfies 在 5.3 中类型检查更加精确
const pair = ['a', 'b'] satisfies Pair as const;
// pair 类型为 readonly ["a", "b"]--verbatimModuleSyntax
// tsconfig.json
{
"compilerOptions": {
"verbatimModuleSyntax": true // import type 中的 type 关键字不可省略
}
}TS 5.4
NoInfer<T>
// 阻止 TS 从某个位置推断类型
function create<T extends string>(
value: T,
options: NoInfer<Omit<SomeOptions, 'key'>> // 不从 options 推断 T
) { }Object.groupBy / Map.groupBy 类型
// 内置类型支持
const grouped = Object.groupBy([1, 2, 3], x => x % 2 === 0 ? 'even' : 'odd');
// 类型安全小结
| 版本 | 关键特性 |
|---|---|
| 5.2 | using / await using 显式资源管理、装饰器元数据 |
| 5.3 | importAttributes、satisfies 完善、verbatimModuleSyntax |
| 5.4 | NoInfer<T>、groupBy 类型支持 |
