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 Functions 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 = ...givesCannot 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
- 1
At the top of the program, create a type alias
Itemfor{ name: string; price: number }. Then useItemin all three places instead of the long type. - 2
Below the shield, create an array
shopWindowof typeItem[]with three items:sword,shieldand a new one, the lantern{ name: "Lantern", price: 15 }. - 3
Replace the two
console.loglines at the end with afor...ofloop overshopWindowthat prints the price tag of each item. The program prints:Silver Sword: 120 gold Oak Shield: 45 gold Lantern: 15 gold