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
|
||
|---|---|---|
| .. | ||
| doc_extraction | ||
| authoring_diagnostics_spec.ts | ||
| authoring_inputs_spec.ts | ||
| authoring_models_spec.ts | ||
| authoring_outputs_spec.ts | ||
| authoring_queries_spec.ts | ||
| BUILD.bazel | ||
| component_indexing_spec.ts | ||
| defer_spec.ts | ||
| env.ts | ||
| extended_template_diagnostics_spec.ts | ||
| host_directives_spec.ts | ||
| imports_spec.ts | ||
| incremental_error_spec.ts | ||
| incremental_semantic_changes_spec.ts | ||
| incremental_spec.ts | ||
| incremental_typecheck_spec.ts | ||
| local_compilation_spec.ts | ||
| ls_typecheck_helpers_spec.ts | ||
| monorepo_spec.ts | ||
| ngtsc_spec.ts | ||
| scope_spec.ts | ||
| sourcemap_utils.ts | ||
| standalone_spec.ts | ||
| template_mapping_spec.ts | ||
| template_typecheck_spec.ts | ||
| util.ts | ||
| xi18n_spec.ts | ||