TS

TypeScript Fundamentals

17 lessons

Progress0%
1. Introduction to TypeScript
1What is TypeScript?2Setting Up TypeScript
2. Basic Types
1Primitive Types2Interfaces and Type Aliases
3. Functions and Generics
Typed FunctionsGenerics
4. Classes and OOP
ClassesInheritance and Interfaces
5. Advanced Types
Union and Intersection TypesUtility Types
6. Modules and Decorators
ES Modules
7. Decorators
Class & Method DecoratorsProperty & Parameter Decorators
8. Declaration Files
Writing .d.ts Files@types & DefinitelyTyped
9. Advanced Patterns
Conditional Types & inferTemplate Literal Types & satisfies
All Tutorials
TypeScriptBasic Types
Lesson 4 of 17 min
Chapter 2 · Lesson 2

Interfaces and Type Aliases

Interfaces and type aliases define the shape of objects.

Interface: Defines an object type with named properties.

  • Can be extended with 'extends'
  • Can be implemented by classes
  • Automatically merged (declaration merging)

Type Alias: Creates a new name for any type.

  • More flexible - can alias primitives, unions, etc.
  • Cannot be extended (use intersection instead)
  • No declaration merging

When to Use:

  • Interface: For object shapes, especially in public APIs
  • Type: For unions, intersections, mapped types

Optional Properties: Use ? to make properties optional.

Readonly Properties: Use readonly to prevent modification.

Code Examples

Interfaces and Typestypescript
// Interface
interface User {
  id: number;
  name: string;
  email?: string;           // optional
  readonly createdAt: Date; // cannot be modified
}

const user: User = {
  id: 1,
  name: "Alice",
  createdAt: new Date()
};

// user.createdAt = new Date(); // Error! readonly

// Extending interfaces
interface Employee extends User {
  department: string;
  salary: number;
}

const employee: Employee = {
  id: 2,
  name: "Bob",
  createdAt: new Date(),
  department: "Engineering",
  salary: 100000
};

// Type alias
type Point = {
  x: number;
  y: number;
};

type ID = string | number;  // Union type

// Intersection type
type AdminUser = User & {
  permissions: string[];
};

// Function type
type Callback = (data: string) => void;

// Generic interface
interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

const response: ApiResponse<User[]> = {
  data: [user],
  status: 200,
  message: "Success"
};

console.log(response.data[0].name);

Interfaces and types are often interchangeable. Use interfaces for objects and classes, types for unions and complex types.

Quick Quiz

1. What does the ? after a property name mean?

Was this lesson helpful?

PreviousNext