🔷 TypeScript Q4 / 101

What is type alias?

AI-Powered Answer ✓ Answered

In TypeScript, a type alias is a way to give a new name to an existing type. This doesn't create a new type; it just creates a new name that refers to that type. Type aliases are incredibly versatile and can be used to name primitive types, union types, tuple types, and even complex object shapes.

What is a Type Alias?

A type alias allows you to create a custom name for any type. This improves readability, reduces repetition, and makes complex type definitions easier to manage and reuse throughout your codebase. It essentially acts as a bookmark for a type definition, letting you refer to it with a simpler, more descriptive name.

Syntax

You define a type alias using the type keyword, followed by the alias name, an equals sign, and the type definition.

Alias for a Primitive Type

typescript
type MyString = string;

let greeting: MyString = "Hello, Type Alias!";
console.log(greeting);

Alias for an Object Type

typescript
type User = {
  id: number;
  name: string;
  email?: string;
};

const user1: User = { id: 1, name: "Alice" };
const user2: User = { id: 2, name: "Bob", email: "bob@example.com" };

console.log(user1, user2);

Alias for a Union Type

typescript
type StringOrNumber = string | number;

let value1: StringOrNumber = "TypeScript";
let value2: StringOrNumber = 123;

console.log(value1, value2);

Alias for a Function Signature

typescript
type Greeter = (name: string) => string;

const greet: Greeter = (name) => `Hello, ${name}!`;

console.log(greet("World"));

Use Cases

  • Improving Readability: Providing clearer, more descriptive names for complex or frequently used types.
  • Defining Object Shapes: Reusing object type definitions across multiple parts of an application.
  • Creating Union and Intersection Types: Making complex combinations of types easier to manage.
  • Defining Tuple Types: Naming the expected structure of a tuple.
  • Function Signatures: Describing the shape of a function, including its parameters and return type.
  • Generic Types: Creating generic type aliases that can operate on different types.

Type Aliases vs. Interfaces

While type aliases and interfaces often serve similar purposes for defining object shapes, there are key differences:

FeatureType AliasInterface
Declaration MergingNo (cannot be augmented)Yes (can be augmented by re-declaring)
Extends/ImplementsUses `&` for intersectionUses `extends` keyword
Primitve/Union/Tuple TypesCan name any typeOnly object shapes
Function SignaturesCan name function typesCan define call signatures

In general, use interface when defining public APIs for libraries or when you need declaration merging. Use type when you need to define unions, tuples, primitive aliases, or other types that are not strictly object shapes, or when you prefer a more functional approach to type composition.