# Assertion Functions

> The assertion functions in TypeScript narrow types by throwing an error if a condition is not met.

## What are assertion functions in TypeScript (asserts x is T)?

The functions with the `asserts value is Type` or `asserts condition` return type that throw if the check fails. After the call, TS narrows the type of the checked value for the rest of the scope.

- Topic: Advanced Types
- Type: concept

## Example

Wrong:

```ts
function assertString(value: unknown): boolean {
  return typeof value === 'string';
}
```

Right:

```ts
function assertString(value: unknown): asserts value is string {
  if (typeof value !== 'string') {
    throw new TypeError('Expected a string');
  }
}
```

An assertion function throws on failure, and `asserts value is string` narrows the value after the call.

## Common mistakes

- Returning `false` instead of throwing, so the narrowing lies to the compiler.

## Key points

- The return type is `asserts value is T` or `asserts condition`, and the function throws when the check fails.
- The check in the body really proves the type, TypeScript does not verify it.
- Arrow assertion functions have an explicit type annotation on the variable, or the call reports an error.

## Interview questions

### Assertion function vs type predicate: which should I use?

Use a predicate for `if` checks. Use an assertion when invalid input should stop execution with an error.

### Can an assertion function return a value?

No, its return type is the `asserts` clause, so it either returns nothing or throws.

## Related cards

- [Type Predicates](https://wonderium.dev/ts/type-predicates.md)
- [Non-Null Assertion](https://wonderium.dev/ts/non-null-assertion.md)
- [never](https://wonderium.dev/ts/never.md)
- [unknown](https://wonderium.dev/ts/unknown.md)
- [Function Types](https://wonderium.dev/ts/function.md)

---

- Level: [TypeScript](https://wonderium.dev/ts.md)
- HTML version: https://wonderium.dev/ts/assertion-functions
- Last updated: 2026-11-25
