0
0
Typescriptprogramming~15 mins

Optional elements in tuples in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Optional elements in tuples
📖 Scenario: Imagine you are creating a simple system to store information about books. Some books have a subtitle, but not all. You want to use a tuple to store the title and optionally the subtitle.
🎯 Goal: Build a TypeScript tuple that can hold a book's title and optionally its subtitle using optional elements in tuples.
📋 What You'll Learn
Create a tuple type called Book with a required string for the title and an optional string for the subtitle.
Create a variable called book1 of type Book with only the title.
Create a variable called book2 of type Book with both title and subtitle.
Print both book1 and book2 to the console.
💡 Why This Matters
🌍 Real World
Optional tuple elements help model data where some parts may or may not be present, like subtitles in book titles.
💼 Career
Understanding optional tuple elements is useful for TypeScript developers working with flexible data structures in real-world applications.
Progress0 / 4 steps
1
Create the tuple type with an optional element
Create a tuple type called Book with a required string for the title and an optional string for the subtitle using the syntax [string, string?].
Typescript
Need a hint?

Use string? to mark the subtitle as optional in the tuple type.

2
Create a tuple variable with only the title
Create a variable called book1 of type Book and assign it a tuple with only the title 'The Great Gatsby'.
Typescript
Need a hint?

Assign a tuple with one string element to book1.

3
Create a tuple variable with title and subtitle
Create a variable called book2 of type Book and assign it a tuple with the title 'The Hobbit' and subtitle 'There and Back Again'.
Typescript
Need a hint?

Assign a tuple with two string elements to book2.

4
Print both tuples to the console
Write two console.log statements to print book1 and book2 to the console.
Typescript
Need a hint?

Use console.log(book1); and console.log(book2); to show the tuples.