Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add context about when to use type predicates and assertion functions #3100

Open
wants to merge 2 commits into
base: v2
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion packages/documentation/copy/en/handbook-v2/Narrowing.md
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,9 @@ function example() {

## Using type predicates

We've worked with existing JavaScript constructs to handle narrowing so far, however sometimes you want more direct control over how types change throughout your code.
We've worked with existing JavaScript constructs to handle narrowing so far, however sometimes you want more direct control over how types change throughout your code. Type predicates provide a way to perform type narrowing in scenarios where the TypeScript compiler is *unable* to do so.

Type predicates bypass the TypeScript compiler's type checking. This means that they can be used to change a value's type to an incorrect type. **Type predicates should be a last resort for narrowing that cannot be done any other way.**

To define a user-defined type guard, we simply need to define a function whose return type is a _type predicate_:

Expand Down Expand Up @@ -483,6 +485,11 @@ In addition, classes can [use `this is Type`](/docs/handbook/2/classes.html#this

Types can also be narrowed using [Assertion functions](/docs/handbook/release-notes/typescript-3-7.html#assertion-functions).

As with [type predicates](#using-type-predicates), assertion functions provide a way to perform type narrowing in scenarios where the TypeScript compiler is *unable* to do so.

Assertion functions bypass the TypeScript compiler's type checking. This means that they can be used to change a value's type to an incorrect type. **Assertion functions should be a last resort for narrowing that cannot be done any other way.**


# Discriminated unions

Most of the examples we've looked at so far have focused around narrowing single variables with simple types like `string`, `boolean`, and `number`.
Expand Down