Mark As Completed Discussion

Classes and Objects in TypeScript

The syntax for classes and objects in TypeScript is mostly the same as in JavaScript. However, TypeScript requires that the properties of objects and their types be declared in the class definition. The following example shows how to define the Book class and declare its properties in TypeScript.

TEXT/TYPESCRIPT
1class Book {
2	title: string;
3	author: string;
4	ISBN: integer;
5	numberOfPages: integer;
6	publicationYear: integer;
7	constructor(title, author, ISBN, numberOfPages, publicationYear) {
8		this.title = title;
9		this.author = author;
10		this.ISBN = ISBN;
11		this.numberOfPages = numberOfPages;
12		this.publicationYear = publicationYear;
13	}
14}

TypeScript also allows for properties to have default values if the constructor doesn’t assign any, as shown in the following example.

Note: All properties need to be initialized either in the class or the constructor.

TEXT/TYPESCRIPT
1class Book {
2	title: string;
3	author: string;
4	ISBN: integer;
5	numberOfPages: integer;
6	publicationYear = 2022;
7	constructor(title, author, ISBN, numberOfPages, publicationYear) {
8		this.title = title;
9		this.author = author;
10		this.ISBN = ISBN;
11		this.numberOfPages = numberOfPages;
12		this.publicationYear = publicationYear;
13	}
14}

It can get tiring to write constructors for classes when all they do is set the value for properties with the same name as the parameters. The example above shows how repetitive the constructor definition can get. TypeScript comes with a feature called parameter properties that allows for properties to get declared while being the constructor’s parameters.

For example, the above class definition can be rewritten with parameter properties, as shown below. The public keyword specifies that we can access these properties directly through the objects.

TEXT/TYPESCRIPT
1class Book {
2	constructor(
3		public title: string,
4		public author: string, 
5		public ISBN: integer, 
6		public numberOfPages: integer, 
7		public publicationYear: integer
8	) {}
9}

Class methods in TypeScript can be defined as arrow functions so that we can directly access their values. The following example shows a getter method in TypeScript.

TEXT/TYPESCRIPT
1class Book {
2	constructor(
3		public title: string,
4		public author: string, 
5		public ISBN: integer, 
6		public numberOfPages: integer, 
7		public publicationYear: integer
8	) {}
9	getTitle = () => {
10		return this.title
11	}
12}
13let myBook = new Book(‘Life of Pi’, ‘Yann Martel’, 9780156027328, 352, 2001)
14console.log(myBook.getTitle())
15// prints ‘Life of Pi’ for the myBook object

Lets see if you understood how classes and objects work in TypeScript.