此博客是本人从学生时代开始做笔记所用, 部分是工作所遇问题,做填坑笔记,部分闲来查阅资料,加上自己的理解所总结的学习笔记, 常忙得不可开交,若漏了资料来源,望通知~ 前路漫漫,写点东西告诉自己正在一点点进步,而不要迷失于繁忙。

interface与type

总结自:https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types

 

1、都能用来描述对象与函数,只是写法不同

//对象
interface Point { x: number; y: number; } //函数
interface SetPoint { (x: number, y: number):
void; }
type Point = {
  x: number;
  y: number;
};

type SetPoint = (x: number, y: number) => void;

 

2、type还可以用来描述原始类型、联合类型以及元组

// primitive
type Name = string;// union
type PartialPoint = PartialPointX | PartialPointY;

// tuple
type Data = [number, string];

 

3、都能实现继承(写法不同),且可交叉继承(interface继承type,type继承interface)

 

interface继承interface(extends)

interface PartialPointX { x: number; }
interface Point extends PartialPointX { y: number; }

 

type继承type(&)

type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };

 

interface继承type (同interface继承interface)

type PartialPointX = { x: number; };
interface Point extends PartialPointX { y: number; }

 

type继承interface (同type继承type)

interface PartialPointX { x: number; }
type Point = PartialPointX & { y: number; };

 

4、类可实现interface与type,方式相同(都是implements)

class与interface都是静态的,因此当type用来描述联合类型时不能被实现

interface Point {
  x: number;
  y: number;
}

class SomePoint implements Point {
  x: 1;
  y: 2;
}

type Point2 = {
  x: number;
  y: number;
};

class SomePoint2 implements Point2 {
  x: 1;
  y: 2;
}

type PartialPoint = { x: number; } | { y: number; };

// FIXME: can not implement a union type
class SomePartialPoint implements PartialPoint {
  x: 1;
  y: 2;
}

 

5、interface可被定义多次,且每次定义的属性最后都能合并

// These two declarations become:
// interface Point { x: number; y: number; }
interface Point { x: number; }
interface Point { y: number; }

const point: Point = { x: 1, y: 2 };

 

posted @ 2020-01-31 16:13  炎泽  阅读(990)  评论(0编辑  收藏  举报