On this page
asserts
Prev: `is` | Up: builtins | Next: `infer`
Rel: builtins, Structural Typing & Narrowing
Ref: TypeScript Docs — asserts
Tags: #public #web #typescript #builtins #tier/standard
Syntax & Overview
function assertDefined<T>(v: T): asserts v is NonNullable<T>
Narrows the argument's type for the remainder of the calling block if the function returns normally (without throwing).
Notes & Pitfalls
- Assertion functions narrow types for the rest of the enclosing scope: Must throw when the condition fails (if it returns normally without throwing, TypeScript trusts the assertion).
- Requires an explicit return type annotation (
asserts val is T).
Example
function assertDefined<T>(val: T | null | undefined, msg = "Missing"): asserts val is T {
if (val == null) throw new Error(msg);
}
function greet(name?: string): string {
assertDefined(name);
return name.toUpperCase(); // narrowed to `string`
}
Linked from
Related notes
- tuts/typescript/builtins/infer Linked here; links to this page; shared tags: #builtins, #tier, #typescript, #web
- tuts/typescript/builtins/is Linked here; links to this page; shared tags: #builtins, #tier, #typescript, #web
- tuts/typescript/builtins Linked here; links to this page; shared tags: #builtins, #typescript, #web
- tuts/typescript/type_system/structural_typing_and_narrowing Linked here; shared tags: #typescript, #web
- tuts/typescript/builtins/any shared tags: #builtins, #tier, #typescript, #web
- tuts/typescript/builtins/as_const shared tags: #builtins, #tier, #typescript, #web
- tuts/typescript/builtins/enum shared tags: #builtins, #tier, #typescript, #web
- tuts/typescript/builtins/keyof shared tags: #builtins, #tier, #typescript, #web
- tuts/typescript/builtins/namespace shared tags: #builtins, #tier, #typescript, #web
- tuts/typescript/builtins/never shared tags: #builtins, #tier, #typescript, #web