x is T Custom Type Guards & Assertion Functions
Last updated: 2026-10-22
x is T Custom Type Guards & Assertion Functions
When built-in guards (typeof/instanceof/in) fall short, write your own guard function: declare its return type as x is T (a type predicate) and TypeScript narrows x to T in branches where the function returns true. Its sibling is the assertion function (asserts x is T), which does not return a boolean but throws on failure.
| Group | Narrowing & Assertions |
|---|---|
| Kind | Syntax |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
// Type predicate: x is narrowed to T where the function returns true
function isFoo(x: unknown): x is Foo {
return typeof x === "object" && x !== null && "foo" in x;
}
// Assertion function: throws when invalid; x is treated as T afterwards
function assertFoo(x: unknown): asserts x is Foo {
if (!isFoo(x)) throw new Error("not a Foo");
}
⚙️ Parameters
| x is T | Type predicate return type: parameterName is TargetType. The function body must perform a real runtime check |
|---|---|
| asserts x is T | Assertion function return type: throw on failure; code after the call treats x as T |
Returns:A predicate function is an ordinary boolean function at runtime; narrowing happens at compile time. An asserts function returns nothing (void) at runtime and signals failure by throwing.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
failed: 404
data: x,y
(Runtime output after transpilation; once isFailure returns true, res is narrowed to ApiError and res.data type-checks — narrowing is guaranteed statically by tsc, at runtime there are only values)