type 和 interface 的区别
type 可以描述 原始类型
type Name = string
type Name = number
type 可以描述联合类型
type Easing = "ease-in" | "ease-out" | "ease-in-out";
type 可以描述元祖
// 描述元祖
type Easing = [number, string]
都可以描述数组
interface stringArray {
[index: number]: string
}
type StringArray = {
[index: number]: string
}
const myArray: StringArray = ['hello', 'world']
都可以描述对象
interface LabeledValue {
label: string;
}
type LabeledValue = {
label: string;
}
const obj: LabeledValue = {
label: 'nike',
}
描述类
interface ClockInterface {
currentTime: Date;
setTime(d: Date): void;
}
class clock implements ClockInterface {
currentTime: Date = new Date()
setTime(d: Date) {
this.currentTime = d
}
constructor(h: number, m: number) {
}
}
都可以描述函数
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function (src: string, sub: string): boolean {
let result = src.search(sub);
return result > -1;
};
mySearch = function (src, sub) {
let result = src.search(sub);
return result > -1;
};
// use type alias
type SetPoint = (x: number, y: number) => void;
let foo: SetPoint
foo = (x, y) => {}
interface 可以 extends
interface Parent { x: number; }
interface Child extends Parent { y: number }
type Parent = { x: number; }
type Child = Parent & { y: number }
type Parent = { x: number; }
interface Child extends Parent { y: number }
interface Parent { x: number; }
type Child = Parent & { y: number }
interface 可以被 implements
类可以以完全相同的方式实现接口或类型别名。
不能实现联合类型的类型别名
interface Point {
x: number;
y: number;
}
type Point2 = {
x: number;
y: number;
}
class SomePoint implements Point {
x = 1;
y = 2;
}
class SomePoint2 implements Point2 {
x = 1;
y = 2;
}
interface 可以被 declaration merging
interface Point { x: number }
interface Point { y: number }
const point: Point = {
x: 1,
y: 2
}