Sub topic 2
Typing Fields and Setting Initial Values
Assume you know basic TypeScript types, JavaScript classes, and the this keyword. A class field is a named value stored on each instance of a class. TypeScript checks a field's type when you declare, initialize, and update it.
Declaring typed fields
Declare a field inside the class body. You can provide a type, an initial value, or both.
class User {
name: string;
age = 0;
active: boolean = true;
constructor(name: string) {
this.name = name;
}
}
const user = new User("Mina");
console.log(user.name); // Mina
console.log(user.age); // 0
console.log(user.active); // trueThe name field has an explicit type but receives its value in the constructor. The age field gets the type number from its initializer. The active field has both an explicit type and an initializer.
Type inference means TypeScript determines a type from a value. An initializer is often enough:
class Config {
retries = 3; // number
mode = "safe"; // string
enabled = false; // boolean
}The inferred type still restricts later assignments. config.retries = "three" is an error.
| Declaration | Meaning |
|---|---|
| `count: number` | A number is required, but no value is assigned here |
| `count = 0` | TypeScript infers `number` and assigns `0` |
| `count: number = 0` | Explicitly declares and initializes a number |
Initialization and strict property checking
With strictPropertyInitialization, every field that does not have an initializer must be assigned in the constructor. This catches instances that could contain undefined values by accident.
class Rectangle {
width: number;
height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
area(): number {
return this.width * this.height;
}
}The constructor parameters provide the values, and assignments use this to update the current instance. Every Rectangle therefore has initialized dimensions after construction.
A field can intentionally allow undefined by declaring a union type:
class SearchResult {
query: string;
errorMessage: string | undefined = undefined;
constructor(query: string) {
this.query = query;
}
}The definite assignment assertion, written !, tells the compiler that another part of the program will initialize a field before it is used:
class Service {
connection!: string;
connect(): void {
this.connection = "ready";
}
}Use ! sparingly. It suppresses a check; it does not assign a value at runtime.
Exercise
What is wrong with class Item { price: number; }, and how can you fix it?
Show answer
The field has a type but no runtime value. Add an initializer such as price = 0, or assign this.price in every constructor path.