mirror of
https://github.com/angular/angular
synced 2026-05-24 09:28:37 +00:00
docs: add docs for @switch Exhaustive type checking
(cherry picked from commit 9dc3ca44ec)
This commit is contained in:
parent
6b112e6c6c
commit
1a151f2dae
2 changed files with 54 additions and 0 deletions
|
|
@ -133,3 +133,30 @@ You can specify multiple conditions for a single block by have consecutive `@cas
|
|||
You can optionally include a `@default` block. The content of the `@default` block displays if none of the preceding case expressions match the switch value.
|
||||
|
||||
If no `@case` matches the expression and there is no `@default` block, nothing is shown.
|
||||
|
||||
### Exhaustive type checking
|
||||
|
||||
`@switch` supports exhaustive type checking, allowing Angular to verify at compile time that all possible values of a union type are handled.
|
||||
|
||||
By using `@default never;`, you explicitly declare that no remaining cases should exist. If the union type is later extended and a new case is not covered by an @case, Angular’s template type checker will report an error, helping you catch missing branches early.
|
||||
|
||||
```angular-html
|
||||
@Component({
|
||||
template: `
|
||||
@switch (state) {
|
||||
@case ('loggedOut') {
|
||||
<button>Login</button>
|
||||
}
|
||||
|
||||
@case ('loggedIn') {
|
||||
<p>Welcome back!</p>
|
||||
}
|
||||
|
||||
@default never; // throws because `@case ('loading')` is missing
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AppComponent {
|
||||
state: 'loggedOut' | 'loading' | 'loggedIn' = 'loggedOut';
|
||||
}
|
||||
```
|
||||
|
|
|
|||
|
|
@ -30,3 +30,30 @@ You can specify multiple conditions for a single block by having consecutive `@c
|
|||
|
||||
**`@switch` does not have fallthrough**, so you do not need an equivalent to a `break` or `return`
|
||||
statement.
|
||||
|
||||
### Exhaustive type checking
|
||||
|
||||
`@switch` supports exhaustive type checking, allowing Angular to verify at compile time that all possible values of a union type are handled.
|
||||
|
||||
By using `@default never;`, you explicitly declare that no remaining cases should exist. If the union type is later extended and a new case is not covered by an @case, Angular’s template type checker will report an error, helping you catch missing branches early.
|
||||
|
||||
```angular-html
|
||||
@Component({
|
||||
template: `
|
||||
@switch (state) {
|
||||
@case ('loggedOut') {
|
||||
<button>Login</button>
|
||||
}
|
||||
|
||||
@case ('loggedIn') {
|
||||
<p>Welcome back!</p>
|
||||
}
|
||||
|
||||
@default never; // throws because `@case ('loading')` is missing
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AppComponent {
|
||||
state: 'loggedOut' | 'loading' | 'loggedIn' = 'loggedOut';
|
||||
}
|
||||
```
|
||||
|
|
|
|||
Loading…
Reference in a new issue