0
0
Typescriptprogramming~5 mins

Type alias for objects in Typescript

Choose your learning style9 modes available
Introduction

A type alias lets you give a name to an object shape. This makes your code easier to read and reuse.

When you want to describe the shape of an object clearly.
When you use the same object structure in many places.
When you want to avoid repeating the same object type again and again.
When you want to make your code easier to understand by naming complex object types.
Syntax
Typescript
type Name = {
  property1: type1;
  property2: type2;
  // more properties
};

Use type keyword followed by the alias name and an object shape inside curly braces.

Each property has a name and a type separated by a colon, ending with a semicolon.

Examples
This defines a Person type with name as a string and age as a number.
Typescript
type Person = {
  name: string;
  age: number;
};
This defines a Point type with x and y coordinates as numbers.
Typescript
type Point = {
  x: number;
  y: number;
};
This defines a Product type with three properties: id, price, and inStock.
Typescript
type Product = {
  id: string;
  price: number;
  inStock: boolean;
};
Sample Program

This program defines a Car type alias. Then it creates an object myCar of that type. Finally, it prints a sentence about the car.

Typescript
type Car = {
  make: string;
  model: string;
  year: number;
};

const myCar: Car = {
  make: "Toyota",
  model: "Corolla",
  year: 2020
};

console.log(`I drive a ${myCar.year} ${myCar.make} ${myCar.model}.`);
OutputSuccess
Important Notes

Type aliases do not create new types at runtime. They only help during development.

You can use type aliases to combine other types, not just objects.

Summary

Type aliases give a name to an object shape for easier reuse.

They make your code cleaner and easier to understand.

Use type keyword followed by the object structure inside curly braces.