type 和 interface 的区别

type 可以描述 原始类型

  1. type Name = string
  2. type Name = number

type 可以描述联合类型

  1. type Easing = "ease-in" | "ease-out" | "ease-in-out";

type 可以描述元祖

  1. // 描述元祖
  2. type Easing = [number, string]

都可以描述数组

  1. interface stringArray {
  2. [index: number]: string
  3. }
  4. type StringArray = {
  5. [index: number]: string
  6. }
  7. const myArray: StringArray = ['hello', 'world']

都可以描述对象

  1. interface LabeledValue {
  2. label: string;
  3. }
  4. type LabeledValue = {
  5. label: string;
  6. }
  7. const obj: LabeledValue = {
  8. label: 'nike',
  9. }

描述类

  1. interface ClockInterface {
  2. currentTime: Date;
  3. setTime(d: Date): void;
  4. }
  5. class clock implements ClockInterface {
  6. currentTime: Date = new Date()
  7. setTime(d: Date) {
  8. this.currentTime = d
  9. }
  10. constructor(h: number, m: number) {
  11. }
  12. }

都可以描述函数

  1. interface SearchFunc {
  2. (source: string, subString: string): boolean;
  3. }
  4. let mySearch: SearchFunc;
  5. mySearch = function (src: string, sub: string): boolean {
  6. let result = src.search(sub);
  7. return result > -1;
  8. };
  9. mySearch = function (src, sub) {
  10. let result = src.search(sub);
  11. return result > -1;
  12. };
  13. // use type alias
  14. type SetPoint = (x: number, y: number) => void;
  15. let foo: SetPoint
  16. foo = (x, y) => {}

interface 可以 extends

  1. interface Parent { x: number; }
  2. interface Child extends Parent { y: number }
  3. type Parent = { x: number; }
  4. type Child = Parent & { y: number }
  5. type Parent = { x: number; }
  6. interface Child extends Parent { y: number }
  7. interface Parent { x: number; }
  8. type Child = Parent & { y: number }

interface 可以被 implements

类可以以完全相同的方式实现接口或类型别名。

不能实现联合类型的类型别名

  1. interface Point {
  2. x: number;
  3. y: number;
  4. }
  5. type Point2 = {
  6. x: number;
  7. y: number;
  8. }
  9. class SomePoint implements Point {
  10. x = 1;
  11. y = 2;
  12. }
  13. class SomePoint2 implements Point2 {
  14. x = 1;
  15. y = 2;
  16. }

interface 可以被 declaration merging

  1. interface Point { x: number }
  2. interface Point { y: number }
  3. const point: Point = {
  4. x: 1,
  5. y: 2
  6. }