Type Inference for Class Properties
What you'll learn: How TypeScript automatically determines property types from their initializers and constructor assignments, reducing the need for explicit annotations.
The Core Idea
Just like with variables and function returns, TypeScript can infer the types of class properties based on how you initialize them. This means you often don't need to write explicit type annotations—TypeScript figures it out from context.
Inference from Initializers
When you assign a value directly to a property at declaration, TypeScript infers its type:
class Product {
name = "Default Product"; // inferred as string
price = 0; // inferred as number
available = true; // inferred as boolean
}
const product = new Product();
product.name = "Laptop"; // ✓ OK
product.price = 999; // ✓ OK
product.available = "yes"; // ✗ Error: Type 'string' is not assignable to type 'boolean'
TypeScript looks at the literal values ("Default Product", 0, true) and infers the primitive types.
Inference from Constructor Assignments
TypeScript also infers property types from assignments inside the constructor:
class User {
username;
age;
constructor(username: string, age: number) {
this.username = username; // property inferred as string
this.age = age; // property inferred as number
}
}
const user = new User("alice", 25);
user.age = 26; // ✓ OK
user.username = 123; // ✗ Error: Type 'number' is not assignable to type 'string'
The properties get their types from the constructor parameter types that are assigned to them.
When Inference Helps
Type inference keeps your classes clean and reduces redundancy. Instead of writing types twice, you let the initializer speak for itself. This is especially helpful for simple properties with obvious default values.
Key Takeaway: TypeScript infers class property types from their initial values and constructor assignments, letting you write less boilerplate while maintaining type safety—though uninitialized properties without annotations will need explicit types or definite assignment assertions.