To declare a class in TypeScript, we make use of the class
keyword followed by the class name.
class Student {}
This creates an empty class.
Adding fields in a class
Fields are properties of a class that can be used to assign values. Let’s declare two fields name
and age for our Student
class.
class Student {
name: string;
age: number;
}
Here, we have declared the type of name to be a string and the age to be a number.
Let’s create an object of class Student and assign some values. To create an object we will use the new
keyword.
let student = new Student();
This will create an object student
of class Student. Since we have declared two properties, let’s assign them some values.
student.name = "Bob";
student.age = 12;
console.log(student); // Student {name: 'Bob', age: 12}
If we try to assign a different type to any of the class fields, the typeScript will complain about it.
student.age = "Twelve"; // Type 'string' is not assignable to type 'number'.
How to use constructor() in typescript?
A constructor method in Typescript is used to initialize an object. TypeScript uses the constructor
keyword to declare a constructor within a class. The properties of the class can be initialized within the constructor method.
class Student {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
let student = new Student("Bob", 12);
console.log(student); // Student {name: 'Bob', age: 12}
The constructor method takes two arguments and using the this
keyword we assign the name and age properties. The values for these properties get passed when creating an object new Student('Ron', 1)