TypeScript Function Practice: Describe a Ticket

Typed functions make the expected input and output easier to understand. Here, a ticket object contains a passenger and a seat number. Your job is to turn those fields into a readable label without changing the original ticket.

Before you start: Object properties, function parameters and TypeScript type annotations.

Your task

Create a Ticket type and a describeTicket function that returns the passenger and seat separated by " — ".

Starter code

type Ticket = { passenger: string; seat: number };
const ticket: Ticket = { passenger: "Subo", seat: 12 };

function describeTicket(ticket: Ticket): string {
  // Return the passenger and seat number.
  return "";
}
console.log(describeTicket(ticket));

Expected result

Subo — 12

The quick playground transpiles TypeScript. It is not a replacement for a complete project type checker.

Open this exercise

Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.

Need a hint?

Return a template literal that reads ticket.passenger and ticket.seat, separated by a space, an em dash, and another space.

Show the complete solution and walkthrough
type Ticket = { passenger: string; seat: number };
const ticket: Ticket = { passenger: "Subo", seat: 12 };

function describeTicket(ticket: Ticket): string {
  return `${ticket.passenger} — ${ticket.seat}`;
}
console.log(describeTicket(ticket));
  1. Read the Ticket type: passenger is a string and seat is a number. The function accepts one object with that shape.
  2. Replace the empty return value with a template literal. Interpolation converts the seat number into text as part of the label.
  3. The function returns the string; the console.log call outside it prints the value. For the supplied data, the label is Subo — 12.

A common mistake

Logging inside the function without returning a value does not satisfy the string return contract. Returning a different hard-coded passenger also fails for other tickets.

Try an edge case

Try another passenger and seat. An empty passenger produces an empty name segment; this type annotation does not validate business rules or untrusted JSON at runtime.

Take it one step further

Add an optional coach property. Append the coach only when it is present. Use a full TypeScript type checker to validate the changed function.

Read the typescript tool guide