Sub topic 2
Why Angular Uses TypeScript
This chapter assumes you know modern JavaScript (ES modules, classes, arrow functions) and basic TypeScript syntax: type annotations, interfaces, and what a decorator looks like. You do not need to have built an Angular app yet. The goal is to understand why TypeScript is required in Angular, what the Angular compiler does with it, and which type errors you will meet most often.
TypeScript Is Part of the Framework
React and Vue let you choose between JavaScript and TypeScript. Angular does not. Every Angular project is a TypeScript project, and the Angular compiler is built on top of the TypeScript compiler. This choice affects how Angular works in three ways:
- Static types describe components, services, inputs, and outputs. Your editor and the compiler can then check how these pieces fit together before the code runs.
- Decorators such as
@Componentand@Injectableattach configuration to classes. The Angular compiler reads that configuration at build time. - Template type checking applies TypeScript's checks to your HTML templates as well, so a typo in a template becomes a build error instead of a blank spot on the page.
TypeScript is a superset of JavaScript that adds a type system and compiles down to plain JavaScript. Browsers never see TypeScript. The build turns it into JavaScript, and nearly all type information is erased along the way.
What Static Types Buy You
A large Angular app has hundreds of classes that pass data to each other. Types make those connections explicit. Here is a small example in plain TypeScript, the kind of model and helper you would put next to a component:
// todo.ts
export interface Todo {
id: number;
title: string;
done: boolean;
}
export function remaining(todos: Todo[]): number {
return todos.filter((t) => !t.done).length;
}
const todos: Todo[] = [
{ id: 1, title: 'Install the CLI', done: true },
{ id: 2, title: 'Create a project', done: false },
];
console.log(remaining(todos)); // 1
// The following lines would fail to compile:
// remaining([{ id: 3, title: 'Typo', don: false }]);
// error: Object literal may only specify known properties, and 'don' does not exist in type 'Todo'.
// const n: string = remaining(todos);
// error: Type 'number' is not assignable to type 'string'.You can run this file with npx tsx todo.ts, or compile it with npx tsc todo.ts and then run node todo.js. The commented lines show errors that JavaScript would only reveal at runtime, if at all.
In Angular, the same checks cover framework APIs. Many of them are generic, which means the type you supply flows through to everything that uses it:
| API | Example | What the type controls |
|---|---|---|
| `signal<T>()` | `signal<Todo[]>([])` | What `set()` and `update()` accept and what reading the signal returns |
| `input<T>()` | `input<string>('')` | What a parent may bind to the input |
| `output<T>()` | `output<Todo>()` | What `emit()` accepts and what the parent's handler receives |
| `inject(Token)` | `inject(TodoService)` | The type of the injected instance, inferred from the class |
Later chapters use each of these. For now the point is that you rarely write a type twice. You declare it once and TypeScript infers it everywhere else.
Decorators: Configuration the Compiler Can Read
A decorator is a function applied to a class or class member with the @ syntax. Angular uses decorators to mark what a class is:
import { Component } from '@angular/core';
@Component({
selector: 'app-hello',
template: `<p>Hello, {{ name }}!</p>`,
})
export class Hello {
name = 'Angular';
}Hello is an ordinary class. The @Component decorator tells Angular that the class controls the element <app-hello> and renders the given template.
Internally, the Angular compiler does not wait for the decorator to run in the browser. During the build, also called ahead-of-time (AOT) compilation, it reads the decorator's object literal from the source code, compiles the template into JavaScript instructions, and generates static properties on the class. The decorator call is then removed from the output.
This has a practical consequence. Decorator metadata must be statically analyzable, meaning the compiler can work out its value without running your app.
Strict Mode Is On by Default
ng new generates a tsconfig.json with strict settings turned on. The relevant parts look like this in recent CLI versions:
{
"compilerOptions": {
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"angularCompilerOptions": {
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}The compilerOptions block configures TypeScript itself. The strict flag turns on a group of checks, including strictNullChecks (values that may be null or undefined must be handled) and strictPropertyInitialization (class fields must be assigned a value).
The angularCompilerOptions block configures Angular's own checks. The most important one is strictTemplates.
Template Type Checking
With strictTemplates, the compiler converts each template into hidden TypeScript code and type-checks it. Expressions inside {{ }}, property bindings, and event bindings are all checked against the component class.
import { Component, input } from '@angular/core';
export interface User {
name: string;
}
@Component({
selector: 'app-user-card',
template: `<p>{{ user()?.name ?? 'Guest' }}</p>`,
})
export class UserCard {
user = input<User | null>(null);
}If you write {{ user().name }} instead, the build fails with an error saying the object is possibly null, because the input's type allows null. If you write {{ user()?.nmae }}, the build fails because nmae does not exist on type User. Without template checking, both mistakes would silently render nothing.
Template checks also cover bindings between components. Binding [user]="42" on <app-user-card> is rejected because number is not assignable to User | null.
Common Errors and How to Fix Them
These are the messages intermediate developers hit most in a new Angular project.
| Error message (shortened) | Usual cause | Fix |
|---|---|---|
| Property 'x' has no initializer and is not definitely assigned in the constructor | A class field is declared without a value | Give it an initial value, or use a `signal` or `input` with a default |
| Object is possibly 'null' or 'undefined' | Reading a property on a value whose type includes `null` | Use `?.`, a default with `??`, or guard the code with a check |
| Property 'x' does not exist on type 'Y' | A typo, or a template that refers to something that is not a public member of the class | Fix the name, or add the member to the class |
| Type 'A' is not assignable to type 'B' | A binding or assignment passes the wrong type | Change the value, or widen the declared type if the value is valid |
| Property 'x' is private and only accessible within class | The template refers to a `private` member | Make it `protected` or public. Templates can read `protected` members |
Trade-offs
TypeScript has costs as well as benefits.
- Learning curve. Generics, union types, and strict null handling take practice. You will spend time reading compiler errors early on.
- Build step. You cannot drop a
.tsfile into a browser. The CLI handles this, so in practice the cost is small. - False confidence. Types describe what you claim, not what is true at runtime, as the callout above explains.
In exchange you get editor autocompletion for framework APIs, refactoring that renames a member across classes and templates, and errors caught at build time across a large codebase. Angular is designed for large, long-lived apps, and those benefits grow with the size of the codebase.
Exercise
A component has the field count: number; with no initial value and no constructor. The project uses the default tsconfig from ng new. What happens when you build, and what is the simplest fix?
Show answer
The build fails because strict mode includes strictPropertyInitialization, which reports that 'count' has no initializer and is not definitely assigned. The simplest fix is to give it an initial value, for example count = 0;, which also lets TypeScript infer the type.
Exercise
Why does Angular reject @Component({ selector: 'app-x', template: buildTemplate() }) where buildTemplate is a function you wrote?
Show answer
The Angular compiler reads decorator metadata during the ahead-of-time build without running your code. Calling a function makes the template impossible to analyze statically, so the compiler cannot turn it into rendering instructions and reports an error.
Exercise
A template contains {{ product().price.toFixed(2) }} and product is declared as input<Product | undefined>(). With strictTemplates on, what error appears, and name one way to fix it.
Show answer
The compiler reports that the object is possibly 'undefined', because the input's type includes undefined. One fix is optional chaining with a fallback, such as {{ product()?.price?.toFixed(2) ?? '—' }}. Another is to make the input required with input.required<Product>() so that its type no longer includes undefined.