Sub topic 2
Typing fields and setting initial values
This chapter assumes you know basic TypeScript types, how object literals and this work in JavaScript, and what a class and an instance are. It covers how to declare the data a class holds, how TypeScript decides each field's type, and when initial values are assigned.
Declaring a field
A field is a property declared in the class body, outside any method. Each instance gets its own copy. You can give a field a type annotation, an initializer, or both.
class Task {
title: string = "Untitled";
done = false;
tags: string[] = [];
dueDate?: Date;
readonly createdAt = new Date();
}
const task = new Task();
task.done = true;
console.log(task.title, task.done, task.tags, task.dueDate);
// Untitled true [] undefined
// task.done = "yes"; // Error: Type 'string' is not assignable to type 'boolean'.The five fields use different forms:
| Declaration | Resulting type | Notes | Column |
|---|---|---|---|
| `title: string = "Untitled"` | `string` | Explicit annotation plus initializer | |
| `done = false` | `boolean` | Type inferred from the initializer | |
| `tags: string[] = []` | `string[]` | The annotation is needed here (see below) | |
| `dueDate?: Date` | `Date \ | undefined` | Optional, so it needs no initializer |
| `readonly createdAt = new Date()` | `Date` | Assigned once, never reassigned |
How the type is inferred
If you write an initializer and no annotation, TypeScript infers the field type the same way it does for a let variable. It widens literals, so done = false becomes boolean and not false.
A readonly field is different. Nothing can reassign it, so TypeScript keeps the literal type.
class Config {
mode = "dark"; // string
readonly version = "v2"; // "v2"
retries = 3; // number
}
const c = new Config();
c.mode = "light"; // OK
// c.version = "v3"; // Error: Cannot assign to 'version' because it is a read-only property.
const v: "v2" = c.version; // OK: the literal type is preservedA field with no annotation and no initializer has an implicit any type. Under noImplicitAny, which strict turns on, this is an error. Always give such a field a type.
When you must annotate
Some initializers tell TypeScript too little.
tags = []infersnever[]understrictNullChecks, so you could not push a string into it. Writetags: string[] = [].owner = nullinfersnull. Writeowner: User | null = null.- A field that starts as one thing and later holds another needs a union annotation, for example
status: "idle" | "busy" = "idle".
Fields without initializers
A field can be declared with only a type. Then it is undefined until something assigns it, usually the constructor.
class User {
name: string;
nickname?: string;
constructor(name: string) {
this.name = name;
}
}
const u = new User("Ada");
console.log(u.name, u.nickname); // Ada undefinednickname?: string has type string | undefined, and you may leave it unassigned. name: string is not optional, so with strictPropertyInitialization enabled the compiler checks that every constructor path assigns it. A later chapter covers that check and the ! escape hatch. Here, treat it as a reminder that a non-optional field must be set either by an initializer or in the constructor.
When initializers run
Initializers are not evaluated once for the class. They run every time you call new, so each instance gets fresh values. This is why tags: string[] = [] is safe: two tasks never share the same array.
The order matters when inheritance is involved:
- For a base class, field initializers run first, then the constructor body.
- For a derived class, the
super()call runs first, including the base class's initializers and constructor body. - The derived class's field initializers run immediately after
super()returns. - The rest of the derived constructor body runs last.
Within one class, initializers run in the order you write them. A later field can therefore use an earlier one through this.
class Rectangle {
width = 4;
height = 3;
area = this.width * this.height; // 12: width and height are already set
}
console.log(new Rectangle().area); // 12If you moved area above width, it would read undefined and compute NaN. TypeScript does report a "used before its initialization" error for direct references like this one.
A gotcha with overridable methods
Because the base constructor finishes before derived fields are set, a base constructor that calls an overridable method can see uninitialized derived fields. TypeScript does not warn about this.
class Greeter {
constructor() {
this.announce();
}
announce(): void {
console.log("hello");
}
}
class LoudGreeter extends Greeter {
suffix = "!";
announce(): void {
console.log("hello" + this.suffix);
}
}
new LoudGreeter(); // helloundefinedWhen Greeter's constructor runs, suffix has not been assigned yet. Avoid calling overridable methods from constructors.
Arrow-function fields and this
A field can hold a function. An arrow function written as an initializer captures this from the instance being built, so it stays bound even when passed around as a callback.
class Button {
label = "Save";
handleClick = (): void => {
console.log(`Clicked ${this.label}`);
};
}
const button = new Button();
const handler = button.handleClick;
handler(); // Clicked SaveThe cost is that each instance gets its own function object, instead of sharing one method on the prototype. Methods are covered in a later chapter.
useDefineForClassFields
The useDefineForClassFields compiler option controls how fields are emitted. It defaults to true when target is ES2022 or later, including ESNext. In that mode, a declaration such as name: string; becomes a real class field, so the property exists and equals undefined right after construction. With older targets and the option off, a field with no initializer emits nothing.
This matters when a subclass redeclares a base field only to narrow its type. With define semantics, the redeclaration resets the value to undefined after super(). Use the declare modifier, as in declare name: string;, to change the type without emitting any field.
Exercise
Given the class below, what does new Box().size evaluate to, and what is the type of items? Fix the declaration so items accepts strings.
class Box {
size = items.length;
items = [];
}
Show answer
The class does not compile as written. size refers to items without this, which names no variable in scope. Even with this.items.length, items is declared later, so TypeScript reports it is used before its initialization, and at runtime it would be undefined. Also, items = [] infers never[] under strictNullChecks. The fix puts items first and annotates it: items: string[] = []; followed by size = this.items.length;. Then new Box().size is 0.