Naming Shapes With type and interface

Harbor Line’s old JavaScript kept each crossing as one object with a dozen optional properties, and nothing stopped a canceled crossing from showing as boarding. Before the checker can tell those states apart, it needs names for the shapes of data the line works with.

In this lesson, you’ll name the line’s ticket shapes so you write each property once and build a foot ticket and a car ticket from one shared base. You’ll also learn to read interface declarations, the other way TypeScript names an object shape, and be able to say when the choice between type and interface matters. Start with the project that the whole course builds on.

Set Up the Harbor Line Project

Every lesson in this course adds code to one small project, so it’s worth setting it up once. You need Node.js, a terminal, and an editor.

Run node --version to check your Node.js version. Node.js runs .ts files directly from version 22.18 on the 22 release line and from 23.6 on, so any current long-term support (LTS) release works. The examples use Node.js 26.

Create a folder for the project, move into it, and install TypeScript as a dev dependency:

Language: Shell
$ mkdir harbor-line
$ cd harbor-line
$ npm init -y
$ npm install --save-dev typescript

The typescript package gives you tsc, the checker. Next, create tsconfig.json in the folder with the settings the course uses:

Language: JSON Filename: tsconfig.json
{
  "compilerOptions": {
    "module": "nodenext",
    "target": "esnext",
    "strict": true,
    "noEmit": true,
    "verbatimModuleSyntax": true,
    "erasableSyntaxOnly": true
  }
}

These settings turn on strict mode, tell tsc to check without writing any files, and allow only TypeScript syntax that Node.js can run by removing the types. Last, configure the project to use ES modules and add a check script with npm pkg set, which edits package.json for you:

Language: Shell
$ npm pkg set type=module scripts.check="tsc --noEmit"

From here on, the course uses two commands with two jobs. npm run check reads your code before it runs and reports type errors. node <file>.ts strips the types and runs the JavaScript that’s left, without checking anything. Type out the examples as you follow the lesson, and run both commands whenever you change a file.

Build Tickets From a Shared Base

When two named types repeat the same properties, you have to make every change to those properties twice, and nothing warns you when the copies drift apart. You’ve already named object shapes with type: type Name = { ... } gives a shape a name you can write wherever the shape would go.

Harbor Line sells two kinds of ticket at the counter for now: one for a foot passenger and one for a car, with its length in feet and its license plate. Here’s the part of the line’s old JavaScript that defines receiptLine() and two sample tickets:

Language: JavaScript
function receiptLine(ticket) {
  const { id, crossingId, priceCents } = ticket;
  return `${id} on ${crossingId}: ${priceCents} cents`;
}

const miraTicket = {
  id: "T-1041",
  crossingId: "HL-0815",
  priceCents: 850,
  passenger: "Mira Okafor",
};
const tomasTicket = {
  id: "T-1042",
  crossingId: "HL-0815",
  lengthFeet: 15,
  plate: "7KQM214",
};

The receipt only needs the ticket’s id, the crossing it’s for, and its price in cents. To type this code, you’d first name each ticket’s shape the way you already know:

Language: TypeScript
type FootTicket = {
  id: string;
  crossingId: string;
  priceCents: number;
  passenger: string;
};

type CarTicket = {
  id: string;
  crossingId: string;
  priceCents: number;
  lengthFeet: number;
  plate: string;
};

The receipt’s three properties appear in both types. And since receiptLine() should accept any ticket, neither name fits its parameter. FootTicket demands a passenger, and CarTicket demands a plate.

The fix is to name the shared part once and build each ticket from it. Create tickets.ts in harbor-line/ with a TicketBase type, the two tickets built on it, and the old code with its types added:

Language: TypeScript Filename: tickets.ts
 1type TicketBase = {
 2  id: string;
 3  crossingId: string;
 4  priceCents: number;
 5};
 6
 7type FootTicket = TicketBase & { passenger: string };
 8type CarTicket = TicketBase & {
 9  lengthFeet: number;
10  plate: string;
11};
12
13function receiptLine(ticket: TicketBase) {
14  const { id, crossingId, priceCents } = ticket;
15  return `${id} on ${crossingId}: ${priceCents} cents`;
16}
17
18const miraTicket: FootTicket = {
19  id: "T-1041",
20  crossingId: "HL-0815",
21  priceCents: 850,
22  passenger: "Mira Okafor",
23};
24const tomasTicket: CarTicket = {
25  id: "T-1042",
26  crossingId: "HL-0815",
27  lengthFeet: 15,
28  plate: "7KQM214",
29};
30
31console.log(receiptLine(miraTicket));
32console.log(receiptLine(tomasTicket));

TicketBase & { passenger: string } is an intersection type. A value of this type must fit both sides at once, so a FootTicket needs every property of TicketBase plus a passenger. The name comes from the values it allows, which are only those that belong to both types.

Run the file first:

Language: Shell
$ node tickets.ts
T-1041 on HL-0815: 850 cents
T-1042 on HL-0815: undefined cents

Tomás’s receipt shows undefined cents. Node.js ran the file without complaint because it never checks types. Now run the check. Its long output lines are wrapped here for display:

Language: Shell
$ npm run check

> [email protected] check
> tsc --noEmit

tickets.ts:24:7 - error TS2322: Type '{ id: string; crossingId: string;
lengthFeet: number; plate: string; }' is not assignable to type 'CarTicket'.
  Property 'priceCents' is missing in type '{ id: string; crossingId: string;
  lengthFeet: number; plate: string; }' but required in type 'TicketBase'.

24 const tomasTicket: CarTicket = {
         ~~~~~~~~~~~

  tickets.ts:4:3 - 'priceCents' is declared here.
    4   priceCents: number;
        ~~~~~~~~~~

Found 1 error in tickets.ts:24

Read it from the top. Line 24 declares Tomás’s ticket, and the first line says his object doesn’t fit CarTicket. The indented line says why. The object has no priceCents, a property that TicketBase requires and declares on line 4. The & gives CarTicket the base’s properties without spelling them out again.

The old ticket was missing its price, so fix the data, not the type. Add priceCents: 4200, after the crossingId line of Tomás’s ticket. The check is then clean, and his receipt reads T-1042 on HL-0815: 4200 cents.

Why does receiptLine() accept both tickets when its parameter is a TicketBase? The checker compares shapes, not names. A CarTicket has every property a TicketBase needs, so it fits, and the extra lengthFeet and plate don’t matter when you pass a variable. Only an object literal written right where a type is expected gets checked for extra properties.

Spell the Same Shapes With interface

Packages, AI suggestions, and teammates’ code often name object shapes another way, so you need to read that spelling too. An interface is a named object shape, declared with the interface keyword. Here are the three ticket types written as interfaces:

Language: TypeScript
interface TicketBase {
  id: string;
  crossingId: string;
  priceCents: number;
}

interface FootTicket extends TicketBase {
  passenger: string;
}

interface CarTicket extends TicketBase {
  lengthFeet: number;
  plate: string;
}

An interface has no =, so the braces follow the name and any extends clause. The extends TicketBase clause gives FootTicket every property of TicketBase, then adds the ones in the FootTicket braces. It does the job & did in your type version.

The keyword may remind you of a class’s extends, and the idea is similar: start from the base, then add. The comparison stops there, though. An interface creates no class, no constructor, and no object. It’s a list of properties for the checker, and nothing else.

You can confirm that by replacing lines 1 to 11 of tickets.ts with the three interfaces. The check stays clean, and node tickets.ts prints the same two receipt lines. Behind the scenes, Node.js removes an interface the same way it removes a type declaration, so neither one leaves anything in the JavaScript that runs.

If you declare an interface with the same name twice, then TypeScript merges the two declarations. Here’s what the check reports when the interface version of tickets.ts ends with a second declaration, interface CarTicket { hasTrailer: boolean; }. The output is wrapped for display:

Language: Shell
$ npm run check

> [email protected] check
> tsc --noEmit

tickets.ts:27:7 - error TS2741: Property 'hasTrailer' is missing in type
'{ id: string; crossingId: string; priceCents: number; lengthFeet: number;
plate: string; }' but required in type 'CarTicket'.

27 const tomasTicket: CarTicket = {
         ~~~~~~~~~~~

  tickets.ts:39:3 - 'hasTrailer' is declared here.
    39   hasTrailer: boolean;
         ~~~~~~~~~~

Found 1 error in tickets.ts:27

The second declaration adds hasTrailer to the same CarTicket, so every car ticket needs one. Two type declarations with the same name are an error instead: Duplicate identifier 'CarTicket'. You don’t need to try this in your file.

Choose Between type and interface

For shapes like these tickets, the choice between type and interface makes no difference. Both list the same properties, and the checker holds a ticket to either one in the same way.

The difference shows up in two places. First, a type alias can name any type, not only an object shape. Say Harbor Line’s old timetable stored crossing IDs as numbers such as 815, while new code uses strings like "HL-0815".

The line type CrossingId = string | number; names a type that allows either one. That’s the | you’ve seen in array types, and it’s the next lesson’s topic. An interface can’t name it, because an interface only ever describes an object shape.

Second, only interfaces merge, as the repeated CarTicket showed. That matters when a name gets declared twice. A repeated interface adds properties without any warning, and packages sometimes do that on purpose. A repeated type alias is an error.

Teams usually pick one style for object shapes and stick with it. This course uses type for every named type, so object shapes and the unions in later lessons share one style.

Swap the three interfaces at the top of tickets.ts back to the type aliases from the shared-base example, then run npm run check once more. It’s clean, and that’s the version of the file to keep. You’ll still meet interface in other people’s code, and now you can read it as the same kind of shape.

Want to practice telling when the choice matters?

Check Your Understanding

Try these before you open the answers. They use the ticket types from this lesson.

  1. Rewrite interface CarTicket extends TicketBase { lengthFeet: number; plate: string; } as a type alias that builds on the TicketBase type.
  2. A teammate suggests changing type CrossingId = string | number; to an interface to match a package they like. What do you tell them?
  1. Combine the base with the extra properties using &: type CarTicket = TicketBase & { lengthFeet: number; plate: string };. The checker then requires all five properties, as the interface did.
  2. That can’t work. An interface only describes an object shape, and CrossingId is a choice between two primitives, so it has to stay a type alias.

You can now name a shared shape once, build ticket types on it with & or extends, and say when type and interface differ. The course’s first coding exercise is where you’ll put that to work.

Coding exercises run in your browser. You edit the code in the editor, click Run Tests, and get automated feedback from the tests. When a test fails, read its message before you change your code, and use Full screen if you want more room. If you’re new to coding exercises on RealJS, the Contents tab below the exercise’s editor explains how they work in more detail.

Next up is Exercise: Name the Boats and Crew, where you’ll give Harbor Line’s roster of boats and crew members named types of its own.

Become a Member to join the conversation.