✏️ 3.2.0.12 TypeScript Practice Exercises
Goal: Practice the TypeScript concepts from the earlier lessons before starting the project. Work through as many of these as you can on your own. These exercises are for practice - there's no single right answer for most of them.
Set up a small TypeScript project (or use the one you created in the Setting Up TypeScript lesson) to try these out with ts-node.
Exercise 1: Type Annotations and Inference
-
Declare a
constvariable for each of these values without annotations. Hover over each in VS Code to see what TypeScript infers:- Your name (note: avoid naming your variable
nameto prevent conflicts with built-in properties) - Your age
- Whether you prefer dark mode (
trueorfalse) - A list of your three favorite programming languages
- Your name (note: avoid naming your variable
-
Now declare the same four values using
let. What changes about the inferred types? -
Declare an empty array for a shopping list. What does TypeScript infer? Fix it by adding an explicit annotation.
Exercise 2: Object Types
-
Define a
typecalledMoviewith the following properties:title- a stringdirector- a stringyear- a numbergenre- one of:"action","comedy","drama","horror","sci-fi"(use a separatetypealias for this)rating- a number (optional)
-
Create at least three
Movieobjects that satisfy this type. Make sure at least one has a rating and at least one doesn't. -
Create a
Movie[]array containing your three movies.
Exercise 3: Typed Functions
Write the following functions with full type annotations on parameters and return types:
-
getTitle(movie: Movie): string- returns the title of a movie -
filterByGenre(movies: Movie[], genre: Genre): Movie[]- returns all movies of a given genre (use theGenretype you created above) -
createMovie(title: string, director: string, year: number, genre: Genre): Movie- creates and returns a newMovieobject with no rating
Exercise 4: Literal Union Types
-
Create a
Prioritytype that can be"low","medium","high", or"critical". -
Write a function
getPriorityLabel(priority: Priority): stringthat returns a descriptive label for each level (e.g.,"Low priority","Critical - address immediately"). Use aswitchorif/elsechain. -
Call
getPriorityLabelwith"urgent"instead of a valid priority. What does TypeScript say? -
Create a
Statustype that can be"active"or"inactive". Declare a variable of that type, reassign it to the other valid value, then try to assign it"pending". What error do you get? (Note: avoid naming your variablestatusto prevent conflicts with built-in properties.)