Skip to content

Chapter 8 - Ensure code correctness with TypeScript

In this chapter, you will ensure code correctness with TypeScript. This will allow to spot errors early during the development of your application. If a specification changes, Visual Studio Code will inform you all files that need to be updated.

Steps

Create the TypeScript enums and types

TypeScript offers many data structures to add typings to the JavaScript language. You will use two of them, enumeration (enum) and type (type).

The enumeration enumerates will possible values of a given domain.

For this tutorial, you will create an enumeration to list all possible media type the slideshow can play. Here, your slideshow can play two kind of media: images and videos. You will then create an enumeration MediaType that enumerates the values IMAGE and VIDEO.

The type describes the structure of a JavaScript object with the allowed keys and values' types.

For this tutorial, you will create a type to define the structure of a slide in the slideshow. A slide has four properties:

  • src: The source of the media
  • type: The kind of media (image or video);
  • alt: An alternative text that is helpful for accessibility;
  • interval: The interval the slide is shown.

The interval could be optional as well, as Splide sets a default interval for its slides.

You will then create a type Slide with the four properties:

  • src: The source of the media as a string;
  • type: The kind of media (image or video) as a MediaType enum;
  • alt: An alternative text that is helpful for accessibility as a string;
  • interval: The interval the slide is shown as a number.

Finally, you will create a second type to define the structure of a slideshow. A slideshow consists of multiple slides.

You will then the create a type Slideshow as an array of Slide.

Create the enums and types directories to store the TypeScript specification files.

In a terminal, execute the following command(s).
mkdir src/enums
mkdir src/types

Create the MediaType enumeration.

src/enums/media-type.enum.ts
1
2
3
4
export enum MediaType {
	IMAGE = "image",
	VIDEO = "video",
}

Create the Slide type.

src/types/slide.type.ts
1
2
3
4
5
6
7
8
import { MediaType } from "../enums/media-type.enum"

export type Slide = {
	src: string;
	type: MediaType;
	alt: string;
	interval?: number; // (1)!
}
  1. The ? indicates the property interval is optional.

Create the Slideshow type.

src/types/slideshow.type.ts
1
2
3
import { Slide } from "./slide.type"

export type Slideshow = Slide[];

Update the service to use TypeScript's types

Update the AppService service to use the Slide created earlier. This code will not work, this is normal and will be fixed in the next step.

src/app.service.ts
import { Injectable } from '@nestjs/common';
import { Slideshow } from './types/slideshow.type';

const slideshow: Slideshow = [ // (1)!
	{
		src: "https://source.unsplash.com/random?1",
		type: "image",
		alt: "Random photo on Unsplash",
		interval: 5000,
	},
	{
		src: "https://source.unsplash.com/random?2",
		type: "image",
		alt: "Random photo on Unsplash",
		interval: 5000,
	},
	{
		src: "https://source.unsplash.com/random?3",
		type: "image",
		alt: "Random photo on Unsplash",
		interval: 5000,
	},
	{
		src: "http://commondatastorage.googleapis.com/gtv-videos-buckesample/Sintel.mp4",
		type: "video",
		alt: "Sintel: first open movie",
		interval: 10000,
	},
]

@Injectable()
export class AppService {
	getSlideshow() {
		return slideshow;
	}
}
  1. The slideshow (slideshow) is now typed as a slideshow (Slideshow).

Observe Visual Studio Code help

As mentioned earlier, the code made earlier doesn't work as is.

Visual Studio Code should underline the type elements of the slideshow array.

This is because the "image" and "video" types are not considered valide by TypeScript. They should be of type MediaType.

This mechanism helps a lot to easily spot required changes when refactoring or spot errors in your code. It helps you be a better developer by thinking ahead of development on your actual needs for your code.

A developer often states the specification before starting to work to ensure the quality of their application.

You can check all problems in your code by going to View > Problems. It will open a tab with all the issues your code is having (if any) with the help of TypeScript.

Update the service

Update the AppService service to use the MediaType enum. Remove the intervals that are not necessary.

src/app.service
import { Injectable } from '@nestjs/common';
import { MediaType } from './enums/media-type.enum';
import { Slideshow } from './types/slideshow.type';

const slideshow: Slideshow = [
	{
		src: "https://source.unsplash.com/random?1",
		type: MediaType.IMAGE,
		alt: "Random photo on Unsplash", // (1)!
	},
	{
		src: "https://source.unsplash.com/random?2",
		type: MediaType.IMAGE,
		alt: "Random photo on Unsplash",
		interval: 2000, // (2)!
	},
	{
		src: "https://source.unsplash.com/random?3",
		type: MediaType.IMAGE,
		alt: "Random photo on Unsplash", // (3)!
	},
	{
		src: "http://commondatastorage.googleapis.com/gtv-videos-buckesample/Sintel.mp4",
		type: MediaType.VIDEO,
		alt: "Sintel: first open movie",
		interval: 10000,
	},
]

@Injectable()
export class AppService {
	getSlideshow() {
		return slideshow;
	}
}
  1. Removed the interval.
  2. Changed the interval for demonstration purpose.
  3. Removed the interval.

Check the results

Start the application and access http://localhost:3000. You should see the exact same slideshow as earlier.

To stop your NestJS application, press Ctrl+C in your terminal.

Summary

Congrats! You have added TypeScript to help you code and spot errors as early as possible during your development process.

Go further

Change the IMAGE = "image" of the MediaType type to PICTURE = "picture". What you would have to change?

Show me the answer!

The file src/app.service.ts has 3 errors that need to be fixed (the Problems tab helps to quickly identify them). Change all the MediaType.IMAGE values to MediaType.PICTURE to fix the issues.

You will still need to update the Handlebar template. Change #if (eq this.type "image") to #if (eq this.type "picture"). Handlebars is not able to use the JavaScript/TypeScript code to validate the cohesion of the Handlebars code. You will still need to update it by hand as there is no help from the IDE.

Even with the Handlebars flow, it still help to spot issues in the rest of the code. You just need to be aware of changes needed to be done to the templates.

Save your changes. If you didn't stop your NestJS application, it should automatically restart the application. Access http://localhost:3000, refresh the page and you should see the expected result.