Thuta Learning
TypeScript
ExercisesProgrammingIntermediate

Practice Exercises - Set 1 (Basics)

TypeScriptLesson 2730 min

What you'll walk away with

  • Write a numeric function with parameter and return types, and check it against known values
  • Create an interface and an array of objects that match it
  • Explain why filter() keeps the element type while map() changes it, and chain the two
  • Read a compiler error and find which type does not match which

Explain it simply

Explain it simply

This lesson teaches nothing new. It is where you write, by hand, what you read in the basic types, functions and interfaces lessons. Nobody learns to kick a ball by watching videos, and nobody remembers syntax by reading it. Each time you write code, hit an error, read it and fix it, the syntax sticks a little better.

The plan is simple. First read one solved warm-up that uses Movie data. Then solve three Book exercises that have the same shape but different data. Run your own attempt at least once before you open the solution.

Problem → Why → Solution

The problem: code that compiles but is wrong

Most people's first attempt at exercise 3 looks like this. The parameter has a type, so it compiles in strict mode. There is no return type, so TypeScript infers Book[] from filter(). But the exercise asks for title strings.

The bug lives inside the function, yet the symptom shows up somewhere else: join(", ") turns the objects into text and the screen shows "[object Object]". There is no error message, so finding the real mistake takes a while.

attempt.ts
function getAvailableBooks(books: Book[]) {
  return books.filter((b) => b.isAvailable); // forgot map(): this is Book[]
}

const titles = getAvailableBooks(books);
console.log(titles.join(", ")); // [object Object], [object Object]

Why does a return type annotation help?

Without a return type, the code itself decides what the function returns, and wrong code produces a wrong type. Writing : string[] tells the compiler what you want up front, so "Type 'Book[]' is not assignable to type 'string[]'" appears right on the buggy line. (A missing return type is not an implicit any; it is inferred. The implicit any error is about parameters that have no type.)

The four ideas the exercises need

Before starting an exercise, read its function signature first: the signature is the spec. celsiusToFahrenheit(celsius: number): number says "one number in, one number out". If the four ideas below make sense, you can solve all three exercises.

Typed parameters and returns

A parameter type protects callers; a return type protects the function body. In strict mode an untyped parameter is an error, while a missing return type is simply inferred.

How numbers behave

TypeScript has one number type, not separate integers and floats, so 9 / 5 is 1.8, not 1, and celsius * 9 / 5 + 32 works as written. Floating-point results can carry long decimals, so use toFixed() when displaying them.

Interfaces and object literals

With const books: Book[] = [...], every object is checked against Book. A missing field gives "Property 'year' is missing", and a misspelled one gives "Object literal may only specify known properties".

The types of filter() and map()

filter() chooses which elements stay but never changes their type: Book[] in, Book[] out. map() turns each element into something new, so (b) => b.title produces string[]. Answer "which ones?" with filter and "turned into what?" with map.

MethodReturns, when called on Book[]
filter((b) => b.isAvailable)Book[]
map((b) => b.title)string[]
find((b) => b.year > 2020)Book | undefined

When the compiler does complain, read the message from the top. The first line usually has the form "Type 'A' is not assignable to type 'B'": A is what your code actually produced, and B is what the annotation promised. The indented lines below narrow the mismatch down, often to a single property. Jump to the file and line number, look at the value there, and ask which of the two types you really meant. If B is right, fix the code; change the annotation only when B itself was the mistake.

Mental model: the signature is the spec
  1. Read the signature: what in, what out
  2. Let the interface check the data
  3. filter to choose, map to reshape
  4. Run it against known values

Compiling proves the types fit, not that the logic is right; a placeholder such as return 0; compiles too.

General pattern

typescript
function convert(value: number): number {
  return value * factor + offset;
}

interface Thing { name: string; active: boolean }

function activeNames(list: Thing[]): string[] {
  return list.filter((t) => t.active).map((t) => t.name);
}

A function with typed input and output, an interface for the data shape, then a filter + map chain that chooses first and reshapes second.

Solved warm-up: movie data

This warm-up has the same shape as the three exercises but different data: a kilometres-to-miles function, a Movie interface and array, and a filter + map chain that returns the titles you have not watched yet. Read it, close it, then write the Book exercises from memory.

warm-up.ts
// Warm-up 1: typed input, typed output
function kmToMiles(km: number): number {
  return km * 0.621371;
}

// Warm-up 2: an interface and a typed array
interface Movie {
  title: string;
  year: number;
  minutes: number;
  watched: boolean;
}

const movies: Movie[] = [
  { title: "Spirited Away", year: 2001, minutes: 125, watched: true },
  { title: "Inception", year: 2010, minutes: 148, watched: false },
  { title: "Coco", year: 2017, minutes: 105, watched: false },
];

// Warm-up 3: filter() keeps Movie objects, map() turns them into strings
function getUnwatchedTitles(list: Movie[]): string[] {
  return list.filter((m) => !m.watched).map((m) => m.title);
}

console.log(kmToMiles(10).toFixed(2));
console.log(getUnwatchedTitles(movies));

Code breakdown

  1. Typed in, typed outfunction kmToMiles(km: number): number {

    kmToMiles("10") is a compile error, and so is a return statement that is not a number. Exercise 1 has exactly this shape.

  2. Typed array literalconst movies: Movie[] = [

    Every object in the array is checked against Movie; leaving out minutes, or writing "125" as a string, is an error.

  3. Choose, then reshapereturn list.filter((m) => !m.watched).map((m) => m.title);

    filter() still returns Movie[]; only map() turns it into string[]. Remove map() and the : string[] annotation turns that into a compile error.

  4. Format for displayconsole.log(kmToMiles(10).toFixed(2));

    The raw result is 6.21371. toFixed(2) returns a string with two decimals, so 6.21 is printed.

You should see
6.21
[ 'Inception', 'Coco' ]

How to work through the exercises

Copy the starter into a file

Paste the challenge's starter code into practice-1.ts, type-check it with npx tsc --strict --noEmit practice-1.ts, and run it with npx tsx practice-1.ts.

One exercise at a time

Run after each exercise. If you write all three before running anything, the errors mix together and are hard to trace.

Test the edge cases

For Celsius, check 0 → 32, 100 → 212 and -40 → -40. For books, try an empty array and a list where nothing is available; both should give [].

In real projects

In real projects

These exercises look like toys, but their shapes appear in real apps all the time. A weather app receives Celsius from an API and converts it to Fahrenheit based on a user setting. An online bookshop's "In stock only" checkbox is just products.filter((p) => p.inStock), and in React the list is rendered with .map() into elements.

Team projects often enable a lint rule that requires return types on exported functions, such as typescript-eslint's explicit-module-boundary-types. This lesson's problem section is the reason: it stops a change inside one function from silently leaking a different type into other files. Unit conversion is also a classic source of expensive bugs when one part of a system assumes one unit and another part assumes a different one, so teams convert at a single boundary and name values clearly, for example tempCelsius instead of temp.

Common mistakes

Common mistakes

Expecting filter() alone to give titles

filter() only chooses objects; it does not reshape them. To get title strings you must follow it with .map((b) => b.title). With a string[] return type, the compiler catches this immediately.

Getting the formula order wrong

(celsius + 32) * 9 / 5 also returns a number, so it compiles; types do not check formulas. Always test with two known pairs such as 100 → 212 and -40 → -40.

Leaving a placeholder behind

The starter's return 0; and return []; exist only to make it compile. Forget to replace them and there is no error, just 0 and [] in the output, so always look at what it prints.

Mini challenge

Practice Set 1: the Book exercises

Without looking at the warm-up, fill in the four TODOs: 1 converts temperatures, 2 is the Book interface and data, 3 returns available titles, and 4 finds books by author.

  • celsiusToFahrenheit(100) returns 212 and (-40) returns -40
  • All three Book objects have all four fields
  • getAvailableBooks() chains filter() and map() and returns string[]
  • getBooksByAuthor() returns Book[]
practice-1.ts
// Exercise 1
function celsiusToFahrenheit(celsius: number): number {
  // TODO: (celsius * 9/5) + 32
  return 0;
}

// Exercise 2
interface Book {
  title: string;
  author: string;
  year: number;
  isAvailable: boolean;
}

const books: Book[] = [
  // TODO: add 3 book objects (at least one with isAvailable: false)
];

// Exercise 3
function getAvailableBooks(list: Book[]): string[] {
  // TODO: filter() the available books, then map() them to titles
  return [];
}

// Exercise 4
function getBooksByAuthor(list: Book[], author: string): Book[] {
  // TODO: keep only the books by this author
  return [];
}

Expected: It prints 212, -40, an array with the two available titles, and [ 2021 ] for the year of Ko Min's book.

Show hint

In exercise 3, remember the type is still Book[] after filter(). Exercise 4 needs no map() at all, because it returns the Book objects themselves.

Show solution
practice-1.ts
// Exercise 1
function celsiusToFahrenheit(celsius: number): number {
  return (celsius * 9) / 5 + 32;
}

// Exercise 2
interface Book {
  title: string;
  author: string;
  year: number;
  isAvailable: boolean;
}

const books: Book[] = [
  { title: "TypeScript Basics", author: "Aye Aye", year: 2023, isAvailable: true },
  { title: "Node in Practice", author: "Ko Min", year: 2021, isAvailable: false },
  { title: "Clean Functions", author: "Aye Aye", year: 2019, isAvailable: true },
];

// Exercise 3
function getAvailableBooks(list: Book[]): string[] {
  return list.filter((b) => b.isAvailable).map((b) => b.title);
}

// Exercise 4
function getBooksByAuthor(list: Book[], author: string): Book[] {
  return list.filter((b) => b.author === author);
}

console.log(celsiusToFahrenheit(100));
console.log(celsiusToFahrenheit(-40));
console.log(getAvailableBooks(books));
console.log(getBooksByAuthor(books, "Ko Min").map((b) => b.year));

Quick quiz 1 / 3

If books is Book[], what is the type of books.filter((b) => b.isAvailable)?

Quick quiz 2 / 3

What does celsiusToFahrenheit(-40) return?

Quick quiz 3 / 3

In strict mode, which part of function getTitles(books) { return books.map((b) => b.title); } does the compiler reject?

What to remember

  • Read the signature as the spec; a return type makes the bug appear on the line that is wrong
  • filter() chooses without changing the type; map() reshapes
  • Compiling is not the same as correct, so run against known values like 100 → 212 and -40 → -40
  • A typed array literal checks every object against the interface

TypeScript Handbook — TypeScript

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Practice Exercises - Set 1 (Basics) | Thuta Learning