在 TypeScript 中,interface 和 type 都是用来定义类型的关键字,它们看起来很相似,但实际上有着不同的用途和特点。本文将详细介绍 interface 和 type 的区别,以及在实际应用中如何选择使用。
interface 的特点
interface 是 TypeScript 中用来定义对象类型的关键字,它通常用来定义一个对象的形状或结构。interface 可以包含属性、方法、索引签名等,它的语法如下:
interface Person {
name: string;
age: number;
sayHello(): void;
}上面的代码定义了一个 Person 接口,它包含了一个字符串类型的 name 属性、一个数字类型的 age 属性和一个没有返回值的 sayHello 方法。接口中的属性和方法都是可选的,你可以只定义一部分属性和方法,或者一个也不定义。
interface 的另一个特点是可以被继承,一个接口可以继承自另一个接口,这样就能够从一个基础接口派生出多个接口,而不必重复定义相同的属性和方法。例如:
// www.javascriptcn.com code example
interface Animal {
name: string;
age: number;
eat(food: string): void;
}
interface Dog extends Animal {
bark(): void;
}上面的代码定义了一个 Animal 接口和一个 Dog 接口,Dog 接口继承自 Animal 接口,并扩展了一个 bark 方法。
type 的特点
type 是 TypeScript 中用来定义类型别名的关键字,它通常用来定义一个类型的别名或联合类型。type 可以包含基本类型、联合类型、交叉类型等,它的语法如下:
// www.javascriptcn.com code example
type Age = number;
type User = {
name: string;
age: Age;
};
type Person = User & {
sayHello(): void;
};上面的代码定义了一个 Age 类型别名,它是一个数字类型;一个 User 类型别名,它是一个包含 name 和 age 属性的对象类型;一个 Person 类型别名,它是一个 User 类型和一个包含 sayHello 方法的对象类型的交叉类型。
type 的另一个特点是可以用来定义联合类型,例如:
type Status = 'success' | 'error' | 'loading';
上面的代码定义了一个 Status 类型别名,它是一个字符串类型,只能取三个值中的一个。
interface 与 type 的区别
interface 与 type 的最大区别在于语法和用途上的不同。interface 用来定义对象类型,type 用来定义类型别名或联合类型。interface 可以被继承,而 type 不可以。interface 中的属性和方法都是可选的,而 type 中的属性和方法都是必须的。
在实际应用中,我们应该根据具体的场景选择使用 interface 还是 type。如果我们需要定义一个对象的形状或结构,就应该使用 interface;如果我们需要定义一个类型别名或联合类型,就应该使用 type。如果我们需要继承一个接口,就必须使用 interface。
示例代码
下面是一个使用 interface 和 type 的示例代码:
// www.javascriptcn.com code example
interface User {
name: string;
age: number;
}
type Status = 'success' | 'error' | 'loading';
type Response = {
status: Status;
data: User[];
};
function fetchData(): Response {
// 模拟异步请求
return {
status: 'success',
data: [
{ name: '张三', age: 20 },
{ name: '李四', age: 22 },
],
};
}
const response = fetchData();
if (response.status === 'success') {
response.data.forEach((user) => {
console.log(`姓名:${user.name},年龄:${user.age}`);
});
} else {
console.log('请求失败');
}上面的代码定义了一个 User 接口和一个 Status 类型别名,它们分别用来定义用户对象和请求状态。然后定义了一个 Response 类型别名,它包含了一个 status 属性和一个 data 属性,status 属性使用了 Status 类型别名,data 属性使用了 User 对象类型。接着定义了一个 fetchData 函数,它返回一个 Response 类型的对象。最后根据请求结果输出用户信息或请求失败信息。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d45e78a941bf71348403df