目次
Optional Chaining
変数の後に?と付けると、変数がnullやundefinedの場合にTypeScriptがその?の場所で式の実行を停止して、undefinedを返してくれる。
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining
let x = foo?.bar.baz();
このコードは下記コードと同じ意味になる。
let x = foo === null || foo === undefined ? undefined : foo.bar.baz();
Non-null assertion operator
変数の後に!を付けると、非nullおよび非undefinedであることを検証してくれる。e!としたら、nullおよびundefinedを除外したeの型の値を返す。
// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
// Throw exception if e is null or invalid entity
}
function processEntity(e?: Entity) {
validateEntity(e);
let s = e!.name; // Assert that e is non-null and access name
}
Nullish Coalescing
Nullishは、nullかundefinedのどちらの値という意味。
x = A ?? Bと書いた場合、Aの値がnullかundefinedの場合はBの値をxに設定し、それ以外はAの値をxに設定する。
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing
let x = foo ?? bar();
これは下記コードと同じ意味になる。
let x = foo !== null && foo !== undefined ? foo : bar();