「这是我参与2022首次更文挑战的第17天,活动详情查看:2022首次更文挑战」。
前言
今天让我们来讨论一下在TypeScript中, Type与 Interface 这两者之间究竟有什么不同。
在最新的TypeScript的版本中,这两者之间的差别可以说是非常小了。Type 几乎可以覆盖所有使用 Interface 的场景。
Interface与 Type都能够对对象和函数签名的类型进行描述,他们之间仅有语法不同:
// interface
interface IUser {
id: number;
firstName: string;
lastName: string;
}
const user: IUser = {
id: 1,
firtName: 'Saif',
lastName: 'Adnan'
};
// type
type TUser = {
id: number;
firstName: string;
lastName: string;
};
const user: TUser = {
id: 1,
firtName: 'Saif',
lastName: 'Adnan'
};
正如你看到上面的代码,除了语法差异之外,他们之间并无别的不同。Interface 的语法更加类似于声明一个类,而 Type 的语言更加类似于声明一个对象。
Type 和 Interface 也都能够被用作函数签名,如下代码所示:
interface IGetUserFullName {
(user: IUser): string;
}
const getUserFullName: IGetUserFullName = (user) => `${user.firstName} ${user.lastName}`;
type TGetUserFullName = (user: TUser) => string;
const getUserFullName: TGetUserFullName = (user) => `${user.firstName} ${user.lastName}`;
自从TypeScript2.2版本开始,允许 Interface extends Type。
type TAddress = {
city: string;
country: string;
}
interface IUser extends TAddress {}
const user: IUser = {
city: 'Malvern',
country: 'USA'
}
Type vs Interface
现在让我们看看 Type 能够实现但是 Interface 不能实现的Feature。
Only Type work
- 能够为基本数据类型指定别名。例如为独一无二的ID指定别名,可以使其更加的具有可读性。
type UniqueId = string;
interface User {
id: UniqueId;
}
- Tuples 能够让我们在其中包含两种不同的数据类型。
Tuple: 可以看做无法改变大小的常量数组
type Employee = [number, string]
const elon: Employee = [1, 'Elon']
- Intersection (交叉类型)允许我们将两个不同的类型合并为一个类型。
type Name = {
name: string
}
type Age = {
age: number;
}
type Person = Name & Age;
const elon: Person = {
name: 'Elon',
age: 22
}
- Union (联合类型)允许新的类型可以只拥有被联合类型的部分类型。
type A = {
age: number;
}
type B = {
name: string;
}
type C = A | B;
// define only name
const andrew: C = {
name: 'Andrew'
}
// define only age
const justin: C = {
age: 25
}
// or we can define both fields
const kelly: C = {
name: 'Kelly',
age: 29
}
Only Interface work
- Auto Merge 仅仅能在 Interface 中起作用。如果定义了重复的 Type ,编译器会抛出一个错误。
type A = {
name: string
}
type A = {
age: number
}
//Typescript compiler throws errors => Duplicate identifier 'A'
而TypeScript会自动将两个相同名字的 Interface 自动合并。
interface B {
name: string;
}
interface B {
age: number;
}
const bob: B = {
name: 'Bob',
age: 40
};
总结
本文中,我们主要讨论了 type 与 interface 之间的不同。他们的确非常的相似,如何使用完全取决你的需求。
对于第三方库中的API定义,interface 的自动合并的特性常常被使用。
除此之外,我们可以使用其中的任何一种方式,但是在我们代码库中应该使其风格保持统一。
感谢阅读 —— 希望您能从中获益~ Happy coding!
原文地址: