By default, all types in TypeScript allow null
:
function getId(x: Element) {
return x.id;
}
getId(null); // TypeScript does not complain, but this is a runtime error.
TypeScript 2.0 adds support for strict null checks. If you set --strictNullChecks
when running tsc
(or set this flag in your tsconfig.json
), then types no longer permit null
:
function getId(x: Element) {
return x.id;
}
getId(null); // error: Argument of type 'null' is not assignable to parameter of type 'Element'.
You must permit null
values explicitly:
function getId(x: Element|null) {
return x.id; // error TS2531: Object is possibly 'null'.
}
getId(null);
With a proper guard, the code type checks and runs correctly:
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);