mirror of
https://github.com/angular/angular
synced 2026-05-24 09:28:37 +00:00
When an `@if` expression has an alias, only the type of the alias is
currently narrowed. So for example, suppose `value` is `string|undefined`:
```
@if (value; as alias) {
{{ value.length }} <!-- error, value may be undefined -->
{{ alias.length }} <!-- no error, alias is narrowed -->
}
```
This is especially noticeable when the expression contains guards which are
preconditions for the aliased expression:
```
@if (a && b; as alias) {...}
```
In this case, `a` would not be narrowed within the body, even though the
`@if` condition forces it to be truthy. This is a bug.
The reason is that aliased expressions were previously type-checked as:
```
var alias = a && b;
if (alias) {
// nothing other than alias is narrowed
...
}
```
One option considered was to emit `const alias` instead of `var alias`.
TypeScript _does_ trace `const` expressions and narrow their individual
components when the overall expression is guarded:
```
const alias = a && b;
if (alias) {
// a, b are also narrowed
}
```
However, this narrowing has different semantics than if `a && b` appeared
directly in the guard expression. For example, object properties aren't
narrowed with this approach, so component properties (which are referenced
as e.g. `this.a`) would not be narrowed.
Instead, we amend the guard expression to include both the expression _and_ the
alias variable, enforcing that both are narrowed.
```
var alias = a && b;
if ((a && b) && alias) {
// a, b, and alias all narrowed correctly.
}
```
This form ensures all conditions within the guard expression get narrowed
while also narrowing the alias variable type.
Fixes #52855
PR Close #55835
|
||
|---|---|---|
| .. | ||
| compliance | ||
| ngtsc | ||
| BUILD.bazel | ||
| downlevel_decorators_transform_spec.ts | ||
| extract_i18n_spec.ts | ||
| initializer_api_transforms_spec.ts | ||
| mocks.ts | ||
| perform_compile_spec.ts | ||
| perform_watch_spec.ts | ||
| signal_queries_metadata_transform_spec.ts | ||
| test_support.ts | ||
| typescript_support_spec.ts | ||
| version_helpers_spec.ts | ||