Typescript中定义类型的两种方式 type 创建类型别名 interface 接口
相同点: 1.都可以定义一个对象或者函数
interface Person {
name: string;
age: number;
}
interface SetPerson{
(name: string, age: number): void
}
type Person = {
name: number;
age: number;
};
type SetPerson = (name: string, age: number): void
2.另外还有其他相似之处,都可以被继承
interface 和 type 都可以继承。另一个值得注意的是,接口和类型别名并不互斥。类型别名可以继承接口,反之亦然。
注意继承方式不同
对于一个接口,继承另一个接口
interface PartialPointX { x: number; }
interface Point extends PartialPointX { y: number; }
或者,继承一个类型
type PartialPointX = { x: number; };
interface Point extends PartialPointX { y: number; }
类型继承另一个类型:
type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };
或者,继承一个接口:
interface PartialPointX { x: number; }
type Point = PartialPointX & { y: number; };
不同点: interface只能定义对象类型。它们是描述对象及其属性的一种方式 type类型别名使用时,不是在创建或者定义新的类别,而是定义类型的一个别名而已。类型声明可以定义基本类型(没啥大作用),联合类型、元祖等。
- type基本类型、联合类型和元祖
虽然接口可以被扩展和合并,但它们不能以联合和交集的形式组合在一起。类型可以使用联合和交集操作符来形成新的类型。
// 基本类型声明
type Name = string;
// 联合类型
interface Person {
name: Name
}
interface Animal {
age: number
}
type Student = Person & Animal
// 具体定义数组每个位置的类型
type PersonList = [Person, Animal]
2.interface声明合并
接口有两个名称相同会自动合并, 也就是&
而类型两个同名不会合并,会报错
interface Point { x: number; }
interface Point { y: number; }
// interface Point { x: number; y: number; }
const point: Point = { x: 1, y: 2 };
3.interface在接口内部对元祖使用
元组(键值对)只能通过type关键字进行定义。
type Point = [x: number, y: number];
没有办法使用接口声明元组。不过,我们可以在接口内部使用元组
interface Point {
coordinates: [number, number]
}
4.type语句中可以使用typeof获取实例类型进行赋值
// 当你想要获取一个变量的类型时,使用typeof
let div = document.createElement('div');
type B = typeof div;
5.type其他
type StringOrNumber = string | number;
type Text = string | { text: string };
type NameLookup = Dictionary<string, Person>;
type Callback<T> = (data: T) => void;
type Pair<T> = [T, T];
type Coordinates = Pair<number>;
type Tree<T> = T | { left: Tree<T>, right: Tree<T> };
6.类型实现联合类型 类可以实现接口以及类型(TS 2.7+)。但是,类不能实现联合类型。
interface Point {
x: number;
y: number;
}
class SomePoint implements Point {
x = 1;
y = 2;
}
// 通过implements关键字 让class实现接口
type AnotherPoint = {
x: number;
y: number;
};
class SomePoint2 implements AnotherPoint {
x = 1;
y = 2;
}
// 通过implements关键字 让class实现类型
type PartialPoint = { x: number; } | { y: number; };
// Following will throw an error
class SomePartialPoint implements PartialPoint {
x = 1;
y = 2;
}
// 类型是联合类型的话 class类无法通过implements实现
一般来说,能用interface实现,就用interface,如果不能就用type 有公共库或者第三方公共API,保持一致性也不错
链接: www.cnblogs.com/cathy1024/p… www.wisdomgeek.com/development… www.jianshu.com/p/1982c6f0b…