Type Aliases

Writing { name: string; health: number } at every variable, parameter and array that holds a hero is long, and when heroes get a new property, you'd have to change it everywhere. Instead, give the type a name with type, which you used in the previous lesson for function types:

type Hero = { name: string; health: number };

function describeHero(hero: Hero): string {
    return `${hero.name} (${hero.health} health)`;
}

const kira: Hero = { name: "Kira", health: 50 };
const party: Hero[] = [kira, { name: "Bruno", health: 65 }];

for (const hero of party) {
    console.log(describeHero(hero));
}

This prints:

Kira (50 health)
Bruno (65 health)

type Hero = ...; creates a type alias: Hero is now another name for { name: string; health: number }. You can use it wherever a type goes: for variables (kira: Hero), parameters (hero: Hero), return types, and arrays (Hero[] is an array of heroes). When the type changes, you change it in one place.

Type names start with a capital letter (Hero, MagicItem), so you can tell them from variables, which start with a small one. Programmers usually put types at the top of the program.

Error messages now use the name, so they get shorter:

type Hero = { name: string; health: number };

const kira: Hero = { name: "Kira", health: 50 };
console.log(kira.gold);
main.ts(4,18): error TS2339: Property 'gold' does not exist on type 'Hero'.

A type alias exists only for TypeScript. Like every type, it disappears from the JavaScript that runs. So type Hero doesn't create any hero: it only describes what a hero looks like.

Typical mistakes:

  • A missing =: type Item { name: string; price: number }; gives '=' expected.
  • A name written differently. Type names are case-sensitive, like variables: const sword: item = ... gives Cannot find name 'item'. Did you mean 'Item'?
  • Two aliases with the same name: Duplicate identifier 'Item'. Each type name can be used only once.

Instructions

At the top of the program, create a type alias Item for { name: string; price: number }. Then use Item in all three places instead of the long type.

Below the shield, create an array shopWindow of type Item[] with three items: sword, shield and a new one, the lantern { name: "Lantern", price: 15 }.

Replace the two console.log lines at the end with a for...of loop over shopWindow that prints the price tag of each item. The program prints:

Silver Sword: 120 gold
Oak Shield: 45 gold
Lantern: 15 gold

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

2/10