Understanding TypeScript Types and Interfaces


Introduction

TypeScript is known for its strong typing system that allows developers to define and use types. Two of the fundamental concepts in TypeScript are types and interfaces, which provide a way to specify the shape of data. In this guide, we'll explore TypeScript types and interfaces with in-depth explanations and sample code.


Types in TypeScript

Types in TypeScript allow you to define the data structure and type of variables, function parameters, and return values. They provide compile-time checks to catch type-related errors before runtime.


Defining Types

Types can be defined using the type keyword:

type Person = {
name: string;
age: number;
};
const person: Person = {
name: 'Alice',
age: 30,
};

Union and Intersection Types

Types can be combined using union (|) or intersection (&) operators:

type Cat = { name: string };
type Dog = { breed: string };
type Pet = Cat | Dog;
type HybridPet = Cat & Dog;

Type Inference

TypeScript can infer types based on the assigned values:

let message = 'Hello'; // TypeScript infers the type as string
let count = 42; // TypeScript infers the type as number

Interfaces in TypeScript

Interfaces are similar to types but are typically used for defining the shape of objects or classes. They are also used to specify the contract that a class must follow.


Defining Interfaces

Interfaces can be defined using the interface keyword:

interface User {
name: string;
age: number;
}
const user: User = {
name: 'Bob',
age: 25,
};

Implementing Interfaces

Classes can implement interfaces to ensure they follow a specific structure:

interface Shape {
area(): number;
}
class Circle implements Shape {
constructor(private radius: number) {}
area(): number {
return Math.PI * this.radius ** 2;
}
}

Extending Interfaces

Interfaces can extend other interfaces to inherit their members:

interface Person {
name: string;
age: number;
}
interface Employee extends Person {
jobTitle: string;
}

Conclusion

Understanding TypeScript types and interfaces is essential for building robust and maintainable applications. Types provide a way to define the structure of data, while interfaces help specify the contract that objects or classes should follow. By using these features, you can catch type-related errors early in the development process and improve the reliability of your TypeScript code.