一文了解ts中type和interface的区别


在 TypeScript 中,typeinterface 是两种用于定义类型的主要声明。虽然它们有很多相似之处,但在某些方面,它们各自又有不同的特性和使用场景。以前用ts的时候我也很困惑,今天就来理清楚吧。

基本概念

  • type:用于定义新类型的别名,可以是基本类型、联合类型、交叉类型、元组等。

    1. 联合类型:
    1
    2
    // 接收count的参数既可以number又可以string,这就是联合类型,联合类型允许一个值可以是多种类型中的一种,使用 | 符号来表示联合类型
    function getCount(count: number | string) {}

    2.交叉类型:

    1
    2
    3
    4
    5
    6
    7
    8
    // 交叉类型允许你将多个类型组合成一个类型。使用 & 符号来表示交叉类型。它通常用于需要将多个对象的属性合并到一个新对象中的场景。
    interface Name {
    name: string;
    }
    interface Age {
    age: number;
    }
    type Person = Name & Age;
    1. 元组:
    1
    2
    // 元组是一种特殊类型的数组,允许你定义一个固定长度和特定类型的数组。每个元素的类型可以不同,元组的类型在定义时就确定了。
    let user: [number, string] = [1, "Pear"];
  • interface: 用于定义对象的结构,包括属性、方法和其类型。就是描述对象的写法。

1. 定义方式

typeinterface 在定义对象类型时的语法有所不同。

使用 interface

1
2
3
4
5
6
7
interface Person {
name: string;
}

const user: Person = {
name: "pear",
}

使用 type

1
2
3
4
5
6
7
type Person = {
name: string;
}

const user: Person = {
name: "pear",
}

如上所示,typeinterface 可以在定义对象时使用相似的语法,但 interface 更适合用于定义对象的描述。

2. 扩展与实现

interface 具有更强的扩展性。它可以通过继承来扩展其他接口,而 type 则使用交叉类型来实现类似的功能。

接口扩展

1
2
3
4
5
6
7
8
9
10
11
12
interface Person {
name: string;
}

interface User extends Person {
username: string;
}

const admin: User = {
name: "pear",
username: "pearpear"
};

类型交叉

1
2
3
4
5
6
7
8
9
10
11
type Person = {
name: string;
};
type User = Person & {
username: string;
};

const admin: User = {
name: "pear",
username: "pearpear"
};

虽然可以实现同样的效果,但在复杂的扩展时,interface 提供了更好的可读性和结构化,而type的扩展写起来有点麻烦,可读性还差。

3. 具名和匿名

interface 是具名的,意味着在定义后可以被引用和扩展。而 type 则可以是具名的或匿名的。

具名的 type

1
2
3
4
5
6
7
type Address = {
city: string;
}

const myAddress: Address = {
city: "wx"
}

匿名的 type

1
2
3
4
5
const myAddress: {
city: string;
} = {
city: "wx"
};

在这个例子中,使用 type 定义的地址既可以是具名的也可以是匿名的,而 interface 则始终是具名的。

4. 合并声明

interface 支持声明合并,这意味着如果定义了多个具有相同名称的接口,它们会自动合并为一个接口。type 不支持这种合并。

1
2
3
4
5
6
7
8
9
10
11
12
13
interface Person {
name: string;
}

interface Person {
id: number;
}

// Person 现在包含 name 和 id 属性,它自动合并为一个接口了
const pear: Person = {
name: "pearpear",
id: 888
};

相同名称的 interface 自动合并,而 type 则会导致错误。

5. 适用场景

  • 使用 interface:需要一个对象类型,并且考虑到将来可能会扩展,interface 是更好的选择。
  • 使用 type:需要定义联合类型、元组或者在某种情况下需要混合类型时,type 更加灵活。

ok,这样我们可以区分出typeiinterface了,具体在使用过程中,需要自己去理解和思考到底用哪个。

我的微信公众号: 梨的前端小屋


文章作者: 梨啊梨
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 梨啊梨 !
  目录