Null safety
Nothing in Cast can be null unless its type says so. T | null is "a T or nothing".
There is no undefined.
class Box { value: int = 5; inc(x: int): int { return this.value + x; } }
function read(box: Box | null): int {
if (!box) return -1; // after this line, box is a Box
return box.value;
}
export function main(): void {
let box: Box | null = null;
print(read(box), box?.inc(1) ?? 0);
box = new Box();
if (box != null) print(box.inc(2));
print(box?.value ?? 0);
let n: int | null = 0;
if (n) print("not printed: 0 is false");
print(n ?? 7);
n = null;
print(n ?? 7);
}
-1 0
7
5
0
7
Narrowing
Before you use a nullable value, you must show the compiler it is present. Cast uses TypeScript's flow analysis:
if (x),if (x != null),if (!x) return;,if (!x) continue;x && x.value > 0const y = x ?? fallback;
Using x.member without narrowing is an error:
nullable receiver must be narrowed before member access (or before a method call).
Narrowing tracks local variables and parameters. It is dropped:
- after an assignment to the variable;
- at loop boundaries: a value narrowed before a
fororwhilemust be checked again inside or after the loop; - at
deferboundaries.
// Narrowed before the loop, used after it: check again.
const director = placedObject("director").as<Director>()?.get();
if (!director) return;
let gained = 0;
for (const obj of objects) { gained += obj.coin.value; }
if (director && gained > 0) director.coinGame.score += gained;
?. and ??
a?.bskips the rest of the chain ifaisnull; the result is nullable.a?.method(),a?.[i]andfn?.(x)work the same way.a ?? bisaif present, otherwiseb.bis only evaluated when needed. The left side must be nullable (left operand of '??' must be nullable).
Conditions on nullable numbers and bools
if (n) on an int | null is true only if n is present and non-zero; on a
bool | null, only if present and true. Use n != null to test presence alone.
Nullable value types
A nullable struct, vector or number is stored as the value plus a "present" flag. A
nullable class, array or map is a pointer that may be null. You don't need to think about
this except that T | null of a value type is slightly larger than T.