In this article, we will look at how to write less code when declaring a class using the constructor shorthand available in Typescript.
We will first start by declaring a regular class.
class Student {
name: string;
constructor(name: string) {
this.name = name;
}
}
let student = new Student("Bob");
console.log(student); // Student {name: 'Bob'}
We have a class called Student with the property field name
which is public. We can write the same class using the shorthand as follows:
class Student {
constructor(public name: string) {}
}
let student = new Student("Bob");
console.log(student); // Student {name: 'Bob'}
As you can see, we have omitted the following:
name: string
declaration at the beginning of the class definition.- In constructor method, initialization of the property (
this.name = name
)
Notice, we have passed the access modifier of property name
(in this case, public) along with the parameter to the constructor method. This tells Typescript to create a public property name
and assign it the value passed during instantiation.
Let’s say we want to add another property age
which is private property.
class Student {
name: string;
private 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}
Same can be written as:
class Student {
constructor(public name: string, private age: number) {}
}
let student = new Student("Bob", 12);
console.log(student); // Student {name: 'Bob', age: 12}
This way you can create shorthand code for constructors in TypeScript.