TypeScript 4.4
September 04, 2021
ref: https://devblogs.microsoft.com/typescript/announcing-typescript-4-4/
代入された判別式の control flow analysis
以前の TypeScript では、type guard の判別式を変数に代入した場合、その判別式は機能しない。
ts
functionfoo (arg : unknown) {constargIsString = typeofarg === 'string';if (argIsString ) {console .log (arg .toUpperCase ());// Error! Property 'toUpperCase' does not exist on type 'unknown'.}}
TypeScript 4.4 では、変数をチェックし、内容が判別式であれば変数の型を絞り込むことができる。
シンボルとテンプレート文字列としての Index Signature
TypeScript 4.4 からはシンボルとテンプレート文字列パターンが Index Signature として使用できる
ts
interfaceColors {[sym : symbol]: number;}constred =Symbol ('red');letcolors :Colors = {};colors [red ] = 255;
ts
interfaceOptions {width ?: number;height ?: number;// 任意の`data-`から始まる文字列をプロパティのキーとして使用できる[optName : `data-${string}`]: unknown;}letoption :Options = {width : 100,height : 100,'data-blah': true,};
useUnknownInCatchVariables
オプション
catch
句の変数の型をany
からunknown
に変更するオプション
ts
try {} catch (err ) {}
strict
オプション下では自動的にオンになる。
exactOptionalPropertyTypes
オプション
多くの JavaScript コードでは、存在しないプロパティとundefined
を値として持つプロパティは同一のものとして扱われる。そのため TypeScript でも、オプショナルプロパティは、undefined
とのユニオンタイプとして考えられてきた。例えば、
ts
interfacePerson {name : string;age ?: number;}
これは下記と同様:
ts
interfacePerson {name : string;age ?: number | undefined;}
exactOptionalPropertyTypes
オプション下では、オプショナルプロパティはundefined
とのユニオンタイプを追加しない。存在しないプロパティと区別される。
ts
interfacePerson {name : string;age ?: number;}constType '{ name: string; age: undefined; }' is not assignable to type 'Person' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties. Types of property 'age' are incompatible. Type 'undefined' is not assignable to type 'number'.2375Type '{ name: string; age: undefined; }' is not assignable to type 'Person' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties. Types of property 'age' are incompatible. Type 'undefined' is not assignable to type 'number'.: p Person = {name : 'Daniel',age :undefined ,};
static ブロック
ECMAScript プロポーザルの static ブロックをサポート:
ts
classFoo {staticcount = 0;}