Class Type Annotations
| Since: | TypeScript 1.0(2014) |
|---|
In TypeScript, you can add type annotations to class properties, constructor parameters, and methods. By adding type information on top of JavaScript's class syntax, you can work with object-oriented programming safely.
Syntax
class ClassName {
propertyName: Type;
constructor(arg: Type) {
this.propertyName = arg;
}
methodName(arg: Type): ReturnType {
// ...
}
}
Type annotation targets
| Target | Example | Description |
|---|---|---|
| Property | name: string; | Specifies a type for a class field. |
| Constructor parameter | constructor(id: number) | Adds a type to a parameter passed when creating an instance. |
| Method parameter | greet(name: string) | Specifies the type of a parameter accepted by a method. |
| Method return value | getAge(): number | Specifies the type of the value returned by a method. |
| readonly property | readonly id: number; | Declares a property that cannot be changed after initialization. |
Sample code
class Person {
readonly id: number;
name: string;
age: number;
constructor(id: number, name: string, age: number) {
this.id = id;
this.name = name;
this.age = age;
}
greet(): string {
return `Hi, I'm ${this.name}, ${this.age} years old.`;
}
haveBirthday(): void {
this.age++;
}
}
const member = new Person(1, 'member_1', 28);
console.log(member.greet()); // Hi, I'm member_1, 28 years old.
member.haveBirthday();
console.log(member.age); // 29
// member.id = 99; // Error: cannot assign to a readonly property
// Shorthand for constructor parameters (combined with access modifiers)
class Point {
constructor(
public x: number,
public y: number
) {}
distance(): number {
return Math.sqrt(this.x ** 2 + this.y ** 2);
}
}
const p = new Point(3, 4);
console.log(p.distance()); // 5
Running the above produces the following output:
npx ts-node ts_class_type.ts Hi, I'm member_1, 28 years old. 29 5
Notes
In TypeScript classes, you can either declare a property and then assign it, or use a shorthand syntax that declares and initializes a property at the same time by adding an access modifier (such as public or private) to a constructor parameter.
A property marked with readonly can only be assigned inside the constructor and cannot be changed afterward. This is a fundamental way to enforce immutability in an object.
A class also acts as a type. To apply an interface to a class, use implements; for inheritance, use JavaScript's standard extends keyword.
If you find any errors or copyright issues, please contact us.