let shoppingList = await showQuickPick( "Which fruits do you want to purchase?", SelectionKind.Multiple, ["code秘密花园", "ConardLi", "bananas", "durian"], ); // 堆代码 duidaima.com console.log(`Alright, going out to buy some ${shoppingList.join(", ")}`); // 错误:`join` 方法不存在于 `string | string[]` 类型TypeScript 5.8 引入了更智能的条件类型推断机制。通过定义条件类型 QuickPickReturn,我们可以让函数的返回类型根据 selectionKind 动态变化:
type QuickPickReturn<S extends SelectionKind> = S extends SelectionKind.Multiple ? string[] : string; async function showQuickPick<S extends SelectionKind>( prompt: string, selectionKind: S, items: readonly string[], ): Promise<QuickPickReturn<S>> { // 实现代码 }这样一来,调用者无需手动检查类型,TypeScript 会自动推断出正确的返回类型:
// 返回类型为 string[] let shoppingList: string[] = await showQuickPick( "Which fruits do you want to purchase?", SelectionKind.Multiple, ["code秘密花园", "ConardLi", "bananas", "durian"], ); // 返回类型为 string let dinner: string = await showQuickPick( "What's for dinner tonight?", SelectionKind.Single, ["code秘密花园", "ConardLi", "tacos", "ugh I'm too hungry to think, whatever you want"], );在实现 showQuickPick 函数时,TypeScript 5.8 还改进了对条件类型的控制流分析。例如,当 selectionKind 为 SelectionKind.Single 时,TypeScript 能够自动推断出返回类型应为 string,而无需手动添加类型断言:
if (selectionKind === SelectionKind.Single) { return selectedItems[0]; // 自动推断为 string } else { return selectedItems; // 自动推断为 string[] }如果开发者不小心写错了分支逻辑,TypeScript 也会及时报错,避免潜在的类型问题:
if (selectionKind === SelectionKind.Single) { return selectedItems; // 错误:返回类型应为 string,而不是 string[] } else { return selectedItems[0]; // 错误:返回类型应为 string[],而不是 string }支持 require() 导入 ECMAScript 模块
2.CommonJS 文件不能 require() ESM 文件
// 使用 `--module nodenext` 时,以下代码不会报错 const esmModule = require('./ConardLi.mjs'); --erasableSyntaxOnly 选项最近,Node.js 23.6 取消了对直接运行 TypeScript 文件的实验性支持,但仅支持某些特定的语法结构。Node.js 引入了一个名为 --experimental-strip-types 的模式,要求任何 TypeScript 特有的语法都不能有运行时语义。换句话说,必须能够轻松地从文件中删除任何 TypeScript 特有的语法,留下一个有效的 JavaScript 文件。
4.导入别名
class C { constructor(public x: number) { } // ~~~~~~~~~~~~~~~~ // error! 当启用 'erasableSyntaxOnly' 时,不允许使用这种语法。 }通过启用 --erasableSyntaxOnly,开发者可以确保他们的 TypeScript 代码在 Node.js 中直接运行时不会遇到不支持的语法结构。这不仅提高了代码的兼容性,还减少了在运行时遇到错误的可能性。
export let propName = "ConardLi"; export class MyClass { [propName] = 42; // ~~~~~~~~~~ // error! // 在类属性声明中,计算属性名必须是简单的字面量类型或 'unique symbol' 类型。 }在之前的 TypeScript 版本中,生成的声明文件可能会包含一个索引签名,如下所示:
export declare let propName: string; export declare class MyClass { [x: string]: number; }而在 TypeScript 5.8 中,生成的声明文件将与实际代码匹配:
export declare let propName: string; export declare class MyClass { [propName]: number; }需要注意的是,这并不会在类上创建静态命名的属性。你仍然会得到一个类似于 [x: string]: number 的索引签名。因此,如果你需要使用静态命名的属性,仍然需要使用 unique symbol 或字面量类型。