Sub topic 10
How blocks narrow types in templates
This chapter assumes you know basic TypeScript (union types, null, type guards), Angular components and templates, and signals. It also assumes your project compiles templates with strictTemplates turned on.
Why narrowing matters in a template
Angular checks templates against the types of your component class. Take a signal that holds User | null. A template line like {{ user().name }} is an error under strict null checks, because user() might be null. You normally fix this with a condition, and the type checker has to understand that the condition makes the access safe. This understanding is called narrowing.
Narrowing means the compiler knows a value has a more specific type inside a region of code than it has outside it. In plain TypeScript this happens inside an if:
function greet(name: string | null): string {
if (name !== null) {
return name.toUpperCase(); // name is string here
}
return 'Hello, guest';
}The built-in control flow blocks bring this behavior into templates with no extra setup.
How the template type checker works
For each component, the Angular compiler generates a hidden piece of TypeScript called a type-check block. It mirrors your template as ordinary code, so TypeScript can check every binding and interpolation. The compiler turns each control flow block into the TypeScript statement it resembles:
| Template block | Generated TypeScript statement |
|---|---|
| `@if (a) { ... } @else { ... }` | `if (a) { ... } else { ... }` |
| `@else if (b)` | `else if (b)` |
| `@switch (x) { @case (1) { ... } }` | `switch (x) { case 1: ... }` |
| `@for (item of list; track item.id)` | a loop whose variable has the element type |
Because the generated code is real if and switch statements, TypeScript's own narrowing rules apply to your template expressions.
Narrowing with @if
The simplest case is a plain property or local value that is checked in the condition:
import { Component } from '@angular/core';
interface Profile {
name: string;
nickname: string | null;
}
@Component({
selector: 'app-nickname',
template: `
@if (profile.nickname) {
<p>Also known as {{ profile.nickname.toUpperCase() }}</p>
} @else {
<p>{{ profile.name }} has no nickname.</p>
}
`,
})
export class NicknameComponent {
profile: Profile = { name: 'Ada Lovelace', nickname: null };
}Inside the first branch, profile.nickname is string, so toUpperCase() compiles. Narrowing also works in the @else branch, where the compiler knows the condition was false. That means @else if chains behave like TypeScript else if chains. Each later branch is checked with every earlier condition known to be false:
@if (value === null) {
<p>No value</p>
} @else if (value.length === 0) {
<p>Empty string</p>
} @else {
<p>{{ value }}</p>
}If value is string | null, the @else if already sees a string.
Why narrowing the old way needed extra code
Structural directives such as *ngIf are ordinary classes. The compiler cannot know that *ngIf="x" behaves like an if. NgIf had to opt in by declaring a static member, ngTemplateGuard_ngIf, which told the checker to treat the bound expression as a guard. Any custom structural directive that wanted narrowing needed its own guard member.
The built-in blocks are part of the template syntax. The compiler knows what they mean, so you need no imports, no guard members, and no directive class.
Signals do not narrow across calls
A signal is a function. When you write user(), TypeScript sees a call expression. It does not assume that a second call returns the same value, so it does not narrow the result of a call. This code does not compile under strict checks:
@if (user()) {
<p>{{ user().name }}</p> <!-- error: user() is possibly null -->
}The first user() is checked, but the second user() is a new call whose type is still User | null. The fix is to store the value once. You have two options.
The first option is the alias form of @if. The as clause saves the evaluated condition in a variable, and that variable has the narrowed type:
import { Component, signal } from '@angular/core';
interface User {
name: string;
email: string | null;
}
@Component({
selector: 'app-user-card',
template: `
@if (user(); as u) {
<h2>{{ u.name }}</h2>
@if (u.email) {
<a [href]="'mailto:' + u.email">{{ u.email.toLowerCase() }}</a>
} @else {
<span>No email on file.</span>
}
} @else {
<p>No user selected.</p>
}
`,
})
export class UserCardComponent {
user = signal<User | null>({ name: 'Ada', email: '[email protected]' });
}Here u is a User, not User | null. It cannot change while the block renders, so a check on u.email narrows reliably. The same fix applies to values from the async pipe, because each | async is also a separate expression. Writing @if (user$ | async; as user) subscribes once and gives you a narrowed variable.
The second option is @let, which declares a template variable. Use it when you want to narrow without adding another nesting level, for example before a @switch:
@let current = user();
@if (current) {
<p>{{ current.name }}</p>
}A @let variable cannot be reassigned, so TypeScript can narrow it the same way it narrows a const.
Narrowing with @switch
@switch is emitted as a TypeScript switch statement. This gives you discriminated union narrowing: when the switch expression is a property that distinguishes the members of a union, each @case sees only the matching member.
import { Component, signal } from '@angular/core';
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rect'; width: number; height: number };
@Component({
selector: 'app-shape-info',
template: `
@let s = shape();
@switch (s.kind) {
@case ('circle') {
<p>Circle with radius {{ s.radius }}</p>
}
@case ('rect') {
<p>Rectangle {{ s.width }} by {{ s.height }}</p>
}
}
<button (click)="toggle()">Change shape</button>
`,
})
export class ShapeInfoComponent {
shape = signal<Shape>({ kind: 'circle', radius: 3 });
toggle(): void {
this.shape.update((current) =>
current.kind === 'circle'
? { kind: 'rect', width: 4, height: 2 }
: { kind: 'circle', radius: 3 },
);
}
}Reading s.radius is legal only inside the 'circle' case. Writing s.width there is a compile error. The @let line matters. If you wrote @switch (shape().kind), the checker would narrow only the .kind value of that one call, and shape() would stay a full union inside each case.
Two behaviors come from the underlying switch:
- Cases compare with strict equality (
===), so@case ('1')does not match the number1. - No case falls through. Only the first matching case renders.
Narrowing with type guard functions
Any expression allowed in a template can act as the condition. That includes calls to functions with a type predicate, which is a return type of the form x is T. Put the guard on the component and call it from @if:
import { Component } from '@angular/core';
interface Cat { meow(): string }
interface Dog { bark(): string }
@Component({
selector: 'app-pet',
template: `
@if (isCat(pet)) {
<p>{{ pet.meow() }}</p>
} @else {
<p>{{ pet.bark() }}</p>
}
`,
})
export class PetComponent {
pet: Cat | Dog = { bark: () => 'Woof' };
isCat(value: Cat | Dog): value is Cat {
return 'meow' in value;
}
}Inside the first branch, pet is Cat. In the @else branch it is Dog, because the guard returned false and the only other member of the union is Dog.
Where narrowing stops
Narrowing follows TypeScript's rules, so it has the same limits.
- Calls are not narrowed. This includes signal reads, method calls, and getters that the compiler cannot prove are stable. Use an alias or
@let. - Narrowing of mutable class properties can be lost inside callbacks. Event handlers such as
(click)="..."run later, and the value may have changed by then. If a handler needs the narrowed value, pass the alias:(click)="select(u)"whereucame from@if (...; as u). @fordoes not narrow its collection. It gives the loop variable the element type. Narrowing of the collection itself comes from an enclosing@if.- The non-null assertion
!works in templates (user()!.name), but it silences the checker instead of proving anything. Prefer the alias, and use!only when you know a value is present and cannot express it any other way. - Checking depends on configuration. With
strictTemplatesset totrueinangularCompilerOptionsoftsconfig.json, these errors appear at build time. In the looser basic mode, many of them are not reported.
Quick reference
| Situation | Does narrowing work? | What to do |
|---|---|---|
| `@if (obj.prop)` then `obj.prop.x` | Yes | Nothing |
| `@if (sig())` then `sig().x` | No | Use `@if (sig(); as v)` |
| `@else` after `@if (x === null)` | Yes | Nothing |
| `@switch (s.kind)` on a discriminated union | Yes, if `s` is a stable value | Use `@let s = sig();` first |
| Type guard in `@if (isFoo(x))` | Yes | Nothing |
| Narrowed property used in an event handler | Not reliably | Pass an alias or `@let` variable |
Exercise
This template does not compile with strictTemplates. Why, and how do you fix it? The class has order = signal<{ id: number; note: string | null } | null>(null);
@if (order()) {
<p>Order {{ order().id }}</p>
@if (order().note) {
<p>{{ order().note.trim() }}</p>
}
}
Show answer
Each order() is a separate call, and TypeScript does not narrow call expressions, so every use still has the type {...} | null. Capture the value once with an alias: @if (order(); as o) { <p>Order {{ o.id }}</p> @if (o.note) { <p>{{ o.note.trim() }}</p> } }. The alias o is not null inside the block, and the check on o.note narrows it to string for trim().
Exercise
Given type Result = { status: 'ok'; data: string } | { status: 'error'; message: string } and a signal result of that type, write a template that shows data for the ok case and message for the error case, with correct narrowing.
Show answer
@let r = result(); @switch (r.status) { @case ('ok') { <p>{{ r.data }}</p> } @case ('error') { <p>{{ r.message }}</p> } }. The @let stores the signal value once, so r.status narrows r itself in each case. Using result().status in the switch would not narrow result().
Exercise
Why did *ngIf need a ngTemplateGuard_ngIf member to narrow types, while @if does not?
Show answer
*ngIf is a normal directive class, so the compiler cannot know it behaves like an if. The directive had to declare a guard member to tell the type checker how to narrow. @if is built into the template syntax, and the compiler emits an actual TypeScript if statement in the type-check block, so TypeScript narrows the expression with no extra declaration.