type interface总是傻傻分不清~~~

Type Aliases (type)

type 关键字用于为类型定义一个别名。这可以是基本类型、联合类型、元组、数组、函数等。type 定义的类型在编译后的 JavaScript 代码中会被移除,不会留下任何运行时的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//联合类型
type StringOrNumber = string | number;
type StringOrNumber = 1 | 2;

//数组类型
type Point = number[];

//元组类型
type Point = [number, number];

//函数类型
type Greeter = (name: string) => void;

const myPoint: Point = [10, 20];
const greet: Greeter = function(name) {
console.log("Hello, " + name);
};

Interfaces (interface)

interface 关键字用于定义对象的形状或类的公共结构。它可以包含方法签名、属性和索引签名。接口通常用于对类进行类型检查,确保类实现了接口中定义的所有成员。

1
2
3
4
5
6
7
8
9
10
11
interface Person {
firstName: string;
lastName: string;
age?: number; // 可选属性
}

const person: Person = {
firstName: "John",
lastName: "Doe",
age: 30
};

异同

相同

  1. type和interface都可以用来定义对象和函数

  2. 都可以实现继承

不同

  1. type 可以声明基本类型、联合类型、元组类型、通过typeof 操作符来声明
  2. interface 可以声明合并。

使用场景

1、官方推荐使用 interface,其他无法满足需求的情况下用 type。但是因为联合类型和交叉类型是比较常用的,所以避免不了大量使用 type 的场景,一些复杂类型也需要通过组装后形成类型别名来使用。

2、如果想保持代码统一,还是可选择使用 type。通过上面的对比,type 其实可涵盖 interface 的大部分场景。

3、对于 React 组件中 props 及 state,推荐使用 type,这样能够保证使用组件的地方不能随意在上面添加属性。如果有自定义需求,可通过 HOC(高阶组件)二次封装。

4、编写三方库时使推荐使用 interface,其更加灵活自动的类型合并可应对未知的复杂使用场景。

Enums (enum)

enum 关键字用于定义枚举类型,它是一种特殊的类型,用于定义一组命名的常数。枚举成员被赋值为数字,从 0 开始递增,除非显式地指定一个值。

1
2
3
4
5
6
7
enum Color {
Red,
Green,
Blue
}

const c: Color = Color.Green;

1.数值枚举

在数值枚举中,每个成员默认从 0 开始自动赋值,并且每个成员的值依次递增 1

1
2
3
4
5
6
7
8
9
10
enum Color {
Red,
Green,
Blue
}

// 使用枚举
const favoriteColor: Color = Color.Green;
console.log(favoriteColor); // 输出: 2
console.log(Color[2]); // 输出: "Green"

如果你想要手动指定枚举成员的值,可以这样做:

1
2
3
4
5
6
7
8
enum Color {
Red = 1,
Green = 2,
Blue = 3
}

const favoriteColor: Color = Color.Green;
console.log(favoriteColor); // 输出: 2

2.字符串枚举

字符串枚举使用花括号 {} 定义,并且每个成员必须显式地指定一个字符串值。

1
2
3
4
5
6
7
8
9
enum Color {
Red = "red",
Green = "green",
Blue = "blue"
}

const favoriteColor: Color = Color.Green;
console.log(favoriteColor); // 输出: "green"
console.log(Color["Green"]); // 输出: "green"

3.反向映射

在 TypeScript 的枚举中,你可以通过枚举类型本身来访问枚举成员的名称,这称为反向映射。这在调试时非常有用,因为它允许你通过值快速找到对应的枚举名称。

1
2
3
4
5
6
7
8
9
enum Color {
Red,
Green,
Blue
}

console.log(Color[0]); // 输出: "Red"
console.log(Color[1]); // 输出: "Green"
console.log(Color[2]); // 输出: "Blue"