Sub topic 10
How blocks narrow types in templates
This chapter assumes you know TypeScript union types and basic narrowing (if (x !== null)). It also assumes you have read the earlier chapters on @if and aliases, and that your project enables strictTemplates in tsconfig.json:
{
"angularCompilerOptions": {
"strictTemplates": true
}
}Without that flag, the Angular compiler checks templates much more loosely, and you won't see the errors described below.
Why narrowing works
When Angular compiles in strict mode, it turns each template into hidden TypeScript code and type-checks it. An @if block becomes a real TypeScript if statement, @else becomes else, and @switch becomes switch. TypeScript's normal narrowing rules therefore apply inside the blocks.
Structural directives such as *ngIf needed a special guard declaration to get this effect. Built-in blocks need nothing extra, because the compiler knows what they mean.
Narrowing a component field
Reading a plain property is the simple case:
import { Component } from '@angular/core';
interface User {
name: string;
}
@Component({
selector: 'app-greeting',
template: `
@if (user) {
<p>Hello, {{ user.name }}</p>
} @else {
<p>Please sign in.</p>
}
`,
})
export class GreetingComponent {
user: User | null = null;
}Inside the @if block, user has type User, so user.name compiles. Outside it, the type is still User | null.
The signal gotcha
TypeScript does not narrow the result of a function call. Each call to user() is treated as a new, unknown value. Because a signal is read by calling it, this code fails type checking:
import { Component, signal } from '@angular/core';
interface User {
name: string;
}
@Component({
selector: 'app-broken',
template: `
@if (user()) {
<p>{{ user().name }}</p>
}
`,
})
export class BrokenComponent {
user = signal<User | null>(null);
}The compiler reports that user() is possibly null on the interpolation line. The fix is the alias from the earlier chapter. The alias stores the value once, and its type is the narrowed one:
import { Component, signal } from '@angular/core';
interface User {
name: string;
}
@Component({
selector: 'app-fixed',
template: `
@if (user(); as u) {
<p>{{ u.name }}</p>
}
`,
})
export class FixedComponent {
user = signal<User | null>(null);
}The same applies to user$ | async. The pipe returns User | null, and as user gives you a User inside the block.
Narrowing with @else if and discriminated unions
Each @else if sees the types left over after earlier conditions failed. Discriminated unions work as in TypeScript:
import { Component } from '@angular/core';
type Result =
| { kind: 'ok'; data: string }
| { kind: 'error'; message: string };
@Component({
selector: 'app-result',
template: `
@if (result.kind === 'ok') {
<p>{{ result.data }}</p>
} @else {
<p>{{ result.message }}</p>
}
`,
})
export class ResultComponent {
result: Result = { kind: 'ok', data: 'Saved' };
}In the @else branch, result is the error member, so result.message is valid. A @switch on result.kind follows the same rules, because the compiler emits a TypeScript switch. As with @if, this holds only for expressions TypeScript can narrow, such as property reads. It does not hold for signal calls.
What @for narrows
@for does not narrow anything. It infers the type of the loop variable from the collection. For tasks() of type Task[], the variable task is a Task. @empty has no loop variable. If the collection is nullable, such as Task[] | null, a type error appears on the @for line itself. Guard it with an outer @if and an alias.
Exercise
In a strict-templates project, @if (order()) { {{ order().total }} } fails to compile when order is signal<Order | null>(null). Why does it fail, and how do you fix it?
Show answer
TypeScript does not narrow the result of a function call, so the second order() is still Order | null. Store the value once with an alias: @if (order(); as o) { {{ o.total }} }. Inside the block, o is typed Order.