Constructor and fields
- TypeScript course
- Intermediate
- Lesson 2/89
- 4 min
Learn class fields with the constructor method.
What is a constructor?
The constructor is a special method called automatically when an instance is created with new. It takes parameters and initializes the class fields with this. This way you can provide values all at once when creating an instance.
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const p = new Person("Ada", 30);The this keyword
this refers to the instance the method belongs to. You access that instance's name field with this.name. When the parameter name and the field name are the same, you cannot distinguish them without this.
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}Practice Book class and constructor
Define a Book class with title: string and author: string fields. Add a constructor that takes both parameters and assigns them with this. Create a new Book instance ("TypeScript", "Ada") and print the title field.
Starter code
// Book sınıfı tanımla: title: string, author: string
// constructor ile title ve author al, this ile ata
// yeni Book örneği oluştur
// title alanını yazdırSample solution
class Book {
title: string;
author: string;
constructor(title: string, author: string) {
this.title = title;
this.author = author;
}
}
const book = new Book("TypeScript", "Ada");
console.log(book.title);Expected output
TypeScript
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the purpose of a constructor?
- Add methods
- Define static members
- Initialize fields when a new instance is created Correct answer
- Delete the class
Explanation: The constructor is called automatically when an instance is created with new and initializes the class fields. Deleting the class, adding methods, or defining static members are not the constructor's job.
2 Assign with this
constructor(name: string) {
____.name = name;
}
constructor(name: string) {
this.name = name;
}
Explanation: this refers to the instance the method belongs to. self is Python; that and it are not valid TypeScript keywords.
3 Constructor parts
| Term | Meaning |
|---|---|
constructor |
Constructor method |
this.name = name |
Field initialization |
new Person("Ada", 30) |
Parameterized instance creation |
name: string |
Parameter type |