← 返回课程: TypeScript from scratch

Objects: type vs interface

视频即将上线

Most of the data in an application is objects: users, products, orders, settings. In TypeScript you describe the shape of an object with an object type, and you have two ways to name it: type and interface. They are so similar that many developers use them almost interchangeably, but they have real differences. Today you learn both, their optional and read-only properties, and a simple rule for choosing.

typescript
type User = {
  id: number;
  name: string;
  email?: string;        // optional
  readonly createdAt: Date; // cannot be reassigned
};

interface Product {
  id: number;
  title: string;
  price: number;
  tags?: string[];
}

const user: User = { id: 1, name: 'Ana', createdAt: new Date() };
const product: Product = { id: 7, title: 'Mug', price: 9.5 };

// user.createdAt = new Date(); // error: Cannot assign to 'createdAt' because it is a read-only property
// const bad: User = { id: 2 }; // error: Property 'name' is missing
console.log(user.name, product.title);

Optional and readonly

An optional property carries a question mark and may be missing; when you read it, its type includes undefined, so you must check it. A readonly property can be assigned when the object is created but not changed afterwards. It is a compile-time protection, not a real freeze: at runtime the resulting JavaScript still allows the change. Use readonly for identifiers and data that should not change, and you will avoid accidental mutation bugs.

Extending types

To reuse shapes, an interface is extended with the extends keyword, and a type is combined with the & operator (intersection). The result is similar: an object that must satisfy both shapes. Another difference: if you declare two interfaces with the same name, TypeScript merges them into one (declaration merging), something a type does not allow and gives a duplicate name error. That merging is useful to extend library types, but in application code it is usually a surprise.

typescript
interface Animal {
  name: string;
}

interface Dog extends Animal {
  breed: string;
}

type Timestamps = { createdAt: Date; updatedAt: Date };
type Post = { title: string } & Timestamps;

type Id = string | number;      // type can name any type, interface cannot
type Handler = (event: string) => void;

const rex: Dog = { name: 'Rex', breed: 'Labrador' };
const post: Post = { title: 'Hi', createdAt: new Date(), updatedAt: new Date() };
console.log(rex.breed, post.title);

Which one to choose

  • Use interface to describe the shape of objects and class contracts, especially if others will extend it.
  • Use type for unions, tuples, function types and computed types: an interface cannot express them.
  • The most important thing is to be consistent within the project; any team picks a rule and follows it.

One last practical tip is to name types in the singular and with an initial capital, like User or Product, and to avoid prefixes such as I on interfaces, which are not usual in modern TypeScript. If an object type grows too large, it is a sign it mixes responsibilities: split it into small pieces and combine them with extends or intersections. And do not hesitate to write types before the code that uses them. Defining the shape of the data first forces you to think the problem through clearly, and the rest of the implementation almost writes itself.

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →