interface 和 type 被 TS 设计出来,是完全不同的东西,有各自的职责。
interface 是接口,用于描述一个对象。
type 是类型别名,用于给各种类型定义别名,让 TS 写起来更简洁、清晰。
只是有时候两者都能实现同样的功能,才会经常被混淆,相信看完本文你能分清他俩了。
平时开发中,一般使用组合或者交叉类型的时候,用 type。
一般要用类的 extends 或 implements 时,用 interface。
interface(接口) 是 TS 设计出来用于定义对象类型的,可以对对象的形状进行描述。
interface Person {
name: string
age: number
}
const person: Person = {
name: 'lin',
age: 18
}
type (类型别名),顾名思义,类型别名只是给类型起一个新名字。它并不是一个类型,只是一个别名而已
// 基本类型别名
type UserName = string;
type UserName = string | number;
// 联合类型
type Animal = Pig | Dog | Cat;
type List = [string, boolean, number];
泛型
泛型就像一个占位符一个变量,在使用的时候我们可以将定义好的类型像参数一样传入,原封不动的输出
function getValue<T>(arg:T):T {
return arg;
}