Typescript 3.9 新特性一览
Promise.all 的定义,在 3.7 版本中一些混用 null 或 undefined 的时候的问题已经在 3.9 得到了修复。// @ts-expect-error 新注释的添加JavaScript 中 CommonJS 的自动引入tsconfig.json 文件TypeScript 定义和书写规范上的改动和修复以前的 bugs promise.all & promise.race 等方法做出了更新,但是也制造出了一个问题。在使用 null & undefined 尤其明显。interface Lion {
roar(): void
}
interface Seal {
singKissFromARose(): void
}
async function visitZoo(lionExhibit: Promise, sealExhibit: Promiseundefined>) {
let [lion, seal] = await Promise.all([lionExhibit, sealExhibit]);
lion.roar(); // uh oh
// ~~~~
// Object is possibly 'undefined'.
}
复制代码这种行为就很奇怪了,实际上
sealExhibit当中包含的undefined,相当于是把undefined错误引入了lion type当中, 这里是一个错误引用。
当然在最新的 3.9 版本中修复了这个问题。
awaited typeawaited type 主要是对现在的 promise 更好的定义和使用。预计在 **`3.9`** 发布的,结果微软又跳票了,可以等下一个版本了。Material-ui 与 Styled-Components 等组件会带来极差的编辑 / 编译速度后。主要从联合类型、交叉类型、条件 判断的 type 类型以及各种映射 type 类型的性能问题来优化。 把相关的库编译时间减少了 40% 左右。Visual Studio Code 团队提供的建议,我们发现在执行文件重命名时,单是查明哪些导入语句需要更新就要耗去 5 到 10 秒时间。TypeScript 3.9 调整了内部编译器与语言服务缓存文件的查找方式,顺利解决了这个问题。pull request 的具体优化内容 function hasImportantPermissions(): boolean {
// ...
}
// Oops!
if (hasImportantPermissions) {
// ~~~~~~~~~~~~~~~~~~~~~~~
// This condition will always return true since the function is always defined.
// Did you mean to call it instead?
deleteAllTheImportantFiles();
}
复制代码但是,此错误仅适用于if语句中的条件。现在三元条件(即语法)现在也支持此功能。比如 cond ? trueExpr : falseExpr
declare function listFilesOfDirectory(dirPath: string): string[];
declare function isDirectory(): boolean;
function getAllFiles(startFileName: string) {
const result: string[] = [];
traverse(startFileName);
return result;
function traverse(currentPath: string) {
return isDirectory ?
// ~~~~~~~~~~~
// This condition will always return true
// since the function is always defined.
// Did you mean to call it instead?
listFilesOfDirectory(currentPath).forEach(traverse) :
result.push(currentPath);
}
}
复制代码import * as fs from "fs";const fs = require("fs");TypeScript 现在能够自动检测您所使用的导入类型,保证文件样式简洁而统一。现在有了如下自动引入的功能
const { readFile } = require('fs')// before
let f1 = () => 42
// oops - not the same!
let f2 = () => { 42 }null 断言操作符(!)的可选链(?.)行为不符合直觉。具体来讲,在以往的版本中,代码:
foo?.bar!.baz被解释为等效于以下 JavaScript 代码:
(foo?.bar).baz在以上代码中,括号会阻止可选链的“短路”行为;因此如果未定义
foo为undefined,则访问baz会引发运行时错误。
换句话说,大多数人认为以上原始代码片段应该被解释为在:
foo?.bar.baz中,当 foo 为 undefined 时,计算结果为 undefined。
这是一项重大变化,但我们认为大部分代码在编写时都是为了考虑新的解释场景。如果您希望继续使用旧有行为,则可在!操作符左侧添加括号,如下所示:
(foo?.bar)!.baz