type特点
- 灵活定义:type 可以用来定义基本类型别名、联合类型、交叉类型等多种类型。例如定义基本类型别名:
type StringOrNumber = string | number;
- 不支持声明合并:重复定义相同名称的 type 会报错。例如:
type Point = { x: number; y: number };
// 再次定义会报错
type Point = { z: number };
interface特点
- 声明合并:可以多次定义同名的 interface,编译器会将它们合并。例如:
interface Point { x: number; }
interface Point { y: number; }
let p: Point = { x: 1, y: 2 };
- 主要用于定义对象类型:interface 专门为定义对象类型而生,语法相对简洁。例如:
interface User { name: string; age: number; }
两者区别
- 定义方式:type 使用
type
关键字,interface 使用 interface
关键字。
- 适用类型:type 更通用,能定义各种类型;interface 主要用于对象类型定义。
- 合并能力:interface 支持声明合并,type 不支持。
优先使用 type 的场景
- 定义联合类型或交叉类型:比如定义一个函数参数既可以是字符串又可以是数字的类型。
type Input = string | number;
function printValue(value: Input) {
console.log(value);
}
- 定义基本类型别名:为常用的复杂类型起别名,如函数类型别名。
type MyFunction = (a: number, b: number) => number;
let add: MyFunction = (x, y) => x + y;
优先使用 interface 的场景
- 对象类型定义且可能需要声明合并:比如在不同模块中对同一个对象类型进行扩展。
// module1.ts
interface Config { baseUrl: string; }
// module2.ts
interface Config { apiKey: string; }
// main.ts
let config: Config = { baseUrl: 'http://example.com', apiKey: '12345' };
- 符合面向对象编程风格定义对象结构:当侧重于描述对象的结构和行为契约时。
interface Shape {
area(): number;
}
class Circle implements Shape {
constructor(public radius: number) {}
area() {
return Math.PI * this.radius * this.radius;
}
}