TypeScript v4.4
2021/8/12
Control Flow Analysis of Aliased Conditions
いったん定数に入れた後にも分岐できるようになった
tstype Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; sideLength: number };
function area(shape: Shape): number {
const { kind } = shape;
if (kind === 'circle') {
return Math.PI * shape.radius ** 2;
}
return shape.sideLength ** 2;
}
従来は、
if (shape.kind === 'circle')
のように書かないとダメだった

条件式を変数に入れて、使うタイミングをずらしてもguardできる
tsfunction f(x: string | number | boolean) {
const isString = typeof x === 'string';
const isNumber = typeof x === 'number';
const isStringOrNumber = isString || isNumber;
if (isStringOrNumber) {
x; // 'string | number'.
} else {
x; // 'x' is 'boolean'.
}
}
従来は、
if (typeof x === 'string' || typeof x === 'number')
と書かないとダメだった

コード例が良いね

Symbol and Template String Pattern Index Signatures
keyにsymbolとTemplate Literal Typesを使えるようになった
tsinterface Colors {
[sym: symbol]: number;
}
tsinterface OptionsWithDataProps extends Options {
[optName: `data-${string}`]: unknown;
}
catch (err)
の err
が、もともと any
だったが unknown
になる
recordの optional?: ..
なpropertyに、 undefined
を代入することを禁止する
classに static
blockを導入
tsclass Foo {
static Foo.count = 0;
static {
if (someCondition()) {
Foo.count++;
}
}
}
というかこれ、ECMAScriptに入っているんだ

Spelling Suggestions for JavaScript
@ts-checkを使ったときのJSのスペルチェック
Auto-Imports Show True Paths in Completion Lists
補完するときのpathが見やすくなった
色々速くなった