# Type Predicates

> The type predicates in TypeScript are function return types that narrow the type of an argument.

## How do type predicates (x is T) work in TypeScript?

The return type in the form `value is Type` that tells TS the argument has a specific type if the function returns `true`. Used to create custom type guards, for example to filter `null` values out of an array.

- Topic: Advanced Types
- Type: concept

## Example

Wrong:

```ts
function isUser(value: any): value is User {
  return 'id' in value;
}
```

Right:

```ts
function isUser(value: unknown): value is User {
  return (
    typeof value === 'object' &&
    value !== null &&
    'id' in value &&
    typeof value.id === 'string'
  );
}
```

`unknown` forces real checks; the `any` version throws on `null` and accepts any `id`.

## Common mistakes

- A predicate returns `true` for the wrong shape, and TypeScript trusts it without warning.

## Key points

- The return type is `value is T`, and the body really checks what it claims.
- Array filters that remove `null` narrow the result, e.g. `filter((x): x is User => x !== null)`.
- Predicates check `unknown` input field by field, not by casting the value.

## Interview questions

### Type predicate vs boolean return: what is the difference?

A `boolean` return does not narrow at the call site. `value is T` narrows the argument in the `if` branch.

### Does TypeScript infer type predicates?

Yes, for simple checks such as `x => x !== undefined`, so `filter()` can narrow without an annotation.

## Related cards

- [Assertion Functions](https://wonderium.dev/ts/assertion-functions.md)
- [unknown](https://wonderium.dev/ts/unknown.md)
- [Union Type](https://wonderium.dev/ts/union-type.md)
- [instanceof](https://wonderium.dev/ts/instanceof.md)
- [never](https://wonderium.dev/ts/never.md)

---

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