TypeScript
asserts defined
Learn null checking with asserts x is defined.
asserts defined
asserts x is defined is a special assertion form; it narrows to all types except null and undefined. It's used to guarantee a value exists; especially useful when working with optional or nullable fields.
function assertDefined(x: unknown): asserts x is defined {
if (x === null || x === undefined) {
throw new Error("value is null or undefined");
}
}
const maybe: string | null = "hello";
assertDefined(maybe);
maybe.toUpperCase(); // string, null narrowed away
Use with nullable fields
asserts x is defined is used to narrow a nullable value (e.g. string | null) to string. When working with optional properties, it guarantees the value exists and the subsequent code can be used safely without null checks.
interface User {
email: string | null;
}
function getEmail(u: User): string {
assertDefined(u.email);
return u.email; // string, null narrowed away
}
Exercise Handle a nullable email with assertDefined
Define an assertDefined(x: unknown): asserts x is defined function (with throw new Error("null or undefined") when x === null || x === undefined). Define a User interface with email: string | null. Write a getEmail(u: User): string function: call assertDefined(u.email), then return u.email. Print the result via console.log(getEmail({ email: "a@b.com" })).
Show example solution
function assertDefined(x: unknown): asserts x is defined {
if (x === null || x === undefined) {
throw new Error("null or undefined");
}
}
interface User {
email: string | null;
}
function getEmail(u: User): string {
assertDefined(u.email);
return u.email;
}
console.log(getEmail({ email: "a@b.com" }));
Test yourself
-
What does asserts x is defined do?
- It makes the value undefined
- It makes the type string
- It produces a value at runtime
- It narrows to all types except null and undefined
Show answer
It narrows to all types except null and undefined — asserts x is defined narrows to all types except null and undefined; it reduces a nullable value to its non-null type and makes subsequent code safe.
-
asserts x is defined
function assertDefined(x: unknown): ____ {
if (x === null || x === undefined) throw new Error("null or undefined");
}
Show answer
function assertDefined(x: unknown): asserts x is defined {
if (x === null || x === undefined) throw new Error("null or undefined");
}
-
asserts defined parts
- asserts x is defined
- narrows out null and undefined
- nullable değer
- reduced to string via defined
- x === null || x === undefined
- body check
- opsiyonel özellik
- safe access via defined
Next lesson: Assertion vs throw