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 };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM