npm install typescript
-
提供针对 Aliased Conditions 的控制流分析 (Control Flow Analysis) -
增加 symbol 类型和模板字符串模式的索引签名 -
在 Catch 中的变量默认为 unknown
(--useUnknownInCatchVariables
) -
新增 Exact Optional Property 类型 ( --exactOptionalPropertyTypes
) -
Class static
Blocks -
针对 tsc --help
的升级和改进 -
优化性能 -
针对 JavaScript 的拼写检查 -
Inlay Hints -
破坏性变化
提供针对 Aliased Conditions 的控制流分析 (Control Flow Analysis)
function foo(arg: unknown) {
if (typeof arg === 'string') {
// We know this is a string now.
console.log(arg.toUpperCase())
}
}
function foo(arg: unknown) {
const argIsString = typeof arg === 'string'
if (argIsString) {
console.log(arg.toUpperCase())
// ~~~~~~~~~~~
// Error! Property 'toUpperCase' does not exist on type 'unknown'.
}
}
function foo(arg: unknown) {
const argIsString = typeof arg === 'string'
if (argIsString) {
console.log(arg.toUpperCase())
// works just fine
}
}
增加 symbol 类型和模板字符串模式的索引签名
interface Foo {
name: string
[index: number]: unknown
// ...
}
interface Bar {
[index: string]: unknown
// ...
}
// 只支持 string 和 number
-
string
-
number
-
symbol
-
template string patterns (e.g. hello-${string}
)
interface Foo {
[index: number]: number;
[k: `hello-${string}`]: unknown;
// ...
}
const a: Foo = {
32: 233,
'hello-name': 'xxx'
// correct
helloname: 0,
// error!
}
在 Catch 中的变量默认为unknown
unknown
是最好的做法。现在 TypeScript 4.4 默认设置为 unkown。try {
executeSomeThirdPartyCode();
}
catch (err) { // err: unknown
// Error! Property 'message' does not exist on type 'unknown'.
console.error(err.message);
// Works! We can narrow 'err' from 'unknown' to 'Error'.
if (err instanceof Error) {
console.error(err.message);
}
}
新增 Exact Optional Property 类型
interface Person {
name: string
age?: number
}
// 等价于
interface Person {
name: string
age?: number | undefined
}
const p: Person = {
name: 'Daniel',
age: undefined, // This is okay by default.
}
Object.assign
、 Object.keys
、对象展开 ({ ...obj })
和 for-in 循环等函数和运算符的行为取决于对象上是否实际存在属性。 --exactOptionalPropertyTypes
指定可选属性类型应完全按照书面解释,这意味着| undefined
不会被添加到类型中:// With 'exactOptionalPropertyTypes' on:
const p: Person = {
name: "Daniel",
age: undefined, // Error! undefined isn't a number
};
Class static
Blocks
class Foo {
static count = 0;
// This is a static block:
static {
if (someCondition()) {
Foo.count++;
}
}
}
class Foo {
static #count = 0;
get count() {
return Foo.#count;
}
static {
try {
const lastInstances = loadLastInstances();
Foo.#count += lastInstances.length;
}
catch {}
}
}
实验性的 Inlay 提示
添加针对 JavaScript 的拼写建议
export var inModule = 1
inmodule.toFixed() // errors on exports
function f() {
var locals = 2
locale.toFixed() // errors on locals
}
var object = {
spaaace: 3
}
object.spaaaace // error on read
object.spaace = 2 // error on write
object.fresh = 12 // OK, no spelling correction to offer
END
文章评论