0
0
Typescriptprogramming~5 mins

What structural typing means in Typescript

Choose your learning style9 modes available
Introduction

Structural typing helps TypeScript check if things fit together by their shape, not by their name. It makes code flexible and easy to use.

When you want to check if an object has certain properties without caring about its exact type name.
When you want to use objects from different places but with similar shapes in your functions.
When you want to write functions that accept many kinds of objects as long as they have the needed properties.
When you want to avoid strict class inheritance but still ensure objects have required features.
Syntax
Typescript
interface Shape {
  property1: any;
  property2: any;
}

function useShape(obj: Shape) {
  // use obj.property1 and obj.property2
}

TypeScript checks if the object passed to useShape has the required properties, regardless of its declared type.

This is different from name-based typing where the exact type name must match.

Examples
The object user has extra property city, but it still works because it has name and age.
Typescript
interface Person {
  name: string;
  age: number;
}

function greet(p: Person) {
  console.log(`Hello, ${p.name}`);
}

const user = { name: "Alice", age: 30, city: "NY" };
greet(user);
Here, point matches the shape of Point so it can be used directly.
Typescript
interface Point {
  x: number;
  y: number;
}

const point = { x: 10, y: 20 };

function printPoint(p: Point) {
  console.log(`x: ${p.x}, y: ${p.y}`);
}

printPoint(point);
Sample Program

The object myCar has an extra property year, but TypeScript allows it because myCar has the required make and model properties.

Typescript
interface Car {
  make: string;
  model: string;
}

function showCar(car: Car) {
  console.log(`Car: ${car.make} ${car.model}`);
}

const myCar = { make: "Toyota", model: "Corolla", year: 2020 };
showCar(myCar);
OutputSuccess
Important Notes

Structural typing focuses on what properties an object has, not what it is called.

This makes TypeScript flexible and helps avoid unnecessary strictness.

Summary

Structural typing checks if objects have the needed properties.

It allows using objects with extra or different names if their shape fits.

This helps write flexible and reusable code.