Basic Class Property Typing
You'll learn how to explicitly type class properties in TypeScript and understand when and how the compiler enforces initialization.
The Core Idea
In TypeScript classes, properties need type annotations just like variables. Unlike plain objects or interfaces, class properties exist as actual memory locations on instances, and TypeScript enforces rules about whether they're initialized before use.
Think of class properties like labeled storage bins in a warehouse. Each bin needs:
- A label (the property name)
- A specification of what goes inside (the type annotation)
- Either something placed in it immediately, or a clear promise that it'll be filled before anyone tries to retrieve from it
Basic Property Type Syntax
You annotate class properties using the same colon syntax as other declarations:
class User {
name: string;
age: number;
isActive: boolean;
}
This declares the shape of User instances, but there's a problem: TypeScript's strict mode requires properties to be initialized.
TypeScript's Initialization Rules
By default (with strict mode enabled), TypeScript enforces that properties must be given values either:
- At declaration:
class Config {
timeout: number = 5000;
retries: number = 3;
}
- In the constructor:
class User {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
Without initialization, you'll get an error: "Property 'name' has no initializer and is not definitely assigned in the constructor."
Combining Types with Initialization
You can provide both a type and an initial value:
class Counter {
count: number = 0;
label: string = "Default Counter";
}
The type annotation is technically optional here (TypeScript would infer it), but being explicit improves readability and catches mismatches.
Key Takeaway: Class properties require type annotations and must be initialized either inline or in the constructor—TypeScript won't let you create instances with undefined required properties in strict mode.