TypeScript
厳密なヌルチェック
サーチ…
厳密なヌルチェックの動作
デフォルトでは、TypeScriptのすべての型でnull許されnull :
function getId(x: Element) {
return x.id;
}
getId(null); // TypeScript does not complain, but this is a runtime error.
TypeScript 2.0では厳密なヌルチェックをサポートしています。あなたが設定した場合--strictNullChecks実行する際にtsc (またはあなたにこのフラグを設定tsconfig.json )、その後、種類はもはや許さないnull :
function getId(x: Element) {
return x.id;
}
getId(null); // error: Argument of type 'null' is not assignable to parameter of type 'Element'.
null値を明示的に許可する必要がありnull 。
function getId(x: Element|null) {
return x.id; // error TS2531: Object is possibly 'null'.
}
getId(null);
適切なガードを設定すると、コードの種類が正しくチェックされて実行されます。
function getId(x: Element|null) {
if (x) {
return x.id; // In this branch, x's type is Element
} else {
return null; // In this branch, x's type is null.
}
}
getId(null);
非nullアサーション
非nullアサーション演算子、 ! TypeScriptコンパイラが自動的にその式を推論できない場合、式がnullでもundefinedもないことを宣言できます。
type ListNode = { data: number; next?: ListNode; };
function addNext(node: ListNode) {
if (node.next === undefined) {
node.next = {data: 0};
}
}
function setNextValue(node: ListNode, value: number) {
addNext(node);
// Even though we know `node.next` is defined because we just called `addNext`,
// TypeScript isn't able to infer this in the line of code below:
// node.next.data = value;
// So, we can use the non-null assertion operator, !,
// to assert that node.next isn't undefined and silence the compiler warning
node.next!.data = value;
}
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow