AI Hints
Home›TypeScript Tutorial›Aliases and Interfaces
TypeScript · Lesson 22 of 120

Type Aliases

Name a type.

⏱ 2 min read▶ Video at 17:40🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Writing a long object type again and again is tiring, and error prone. A type alias gives a type a name. Then you use the name everywhere.

Type Aliases
From the video: Type Aliases
  • Long types repeat
  • Give it a name
  • Use the name

A Bike alias

Type Bike names the shape. Now the array, and the function, both use Bike. Run it. Cleaner code, with the same checks.

app.tstypescript
type Bike = {
  model: string;
  price: number;
  stock: number;
};

const bikes: Bike[] = [
  { model: "Trail 500", price: 849.5, stock: 12 },
  { model: "City 200", price: 450, stock: 0 },
];

function inStock(list: Bike[]): string[] {
  return list.filter(b => b.stock > 0).map(b => b.model);
}

console.log(inStock(bikes));
Output
[ 'Trail 500' ]

Aliases name anything

Aliases can name object types, but also simple ones. An order ID can be an alias for number. A list of prices can be an alias. The name explains what the type means.

keyvalue
type Bikean object shape
type OrderId= number
type Prices= number[]
Benefitnames explain meaning

Summary

Type aliases give a name to any type, so you write it once. Next, interfaces.

Key takeaways
  • type Bike = {...}
  • Bike[]
  • Write once
Next up: Interfaces — describe objects