Assertion Functions With asserts Narrowing
Guard a boundary with an assertion function whose asserts return type narrows the caller variable after the call, throwing a TypeError on invalid shapes.
Code
// Assertion function: a return type of asserts value is T narrows the caller
interface Profile {
email: string;
}
function assertProfile(value: unknown): asserts value is Profile {
if (typeof value !== 'object' || value === null) {
throw new TypeError('profile must be an object');
}
if (typeof (value as Record<string, unknown>).email !== 'string') {
throw new TypeError('profile.email must be a string');
}
}
function render(raw: unknown): string {
assertProfile(raw);
// 从这里开始 raw 已收窄为 Profile,直接访问字段不再报错
return raw.email.toLowerCase();
}
console.log(render({ email: '[email protected]' }));
try {
render({ email: 42 });
} catch (error) {
console.log('rejected:', error instanceof TypeError ? error.message : String(error));
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
[email protected]
rejected: profile.email must be a stringHow it works
Assertion Functions With asserts Narrowing keeps everything in the functions assertProfile and render.
The failure path is explicit — TypeError is raised when the guard condition holds.
What to watch for
- The guard
typeof value !== 'object' || value === nullshort-circuits the flow with an earlythrowwhen its condition holds.
Using it
Entry signature: function assertProfile(value: unknown)
Running the file prints labeled results such as rejected: — each operation’s effect is visible in the output.
Key statements
throw new TypeError('profile.email must be a string');
throw new TypeError('profile must be an object');
return raw.email.toLowerCase();
Interactive Tools for This Topic
FAQ
- How does the snippet fail?
- The code throws `TypeError` — the guard `typeof value !== 'object' || value === null` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. The file defines `assertProfile`, `render` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.