Understand the difference between interface and type in three minutes

If you have a certain understanding of typescript, you will find that interface and type are very similar. In terms of type definition, in many cases, it can be implemented in two ways.

Three minutes straight to the topic, in addition to the difference in grammar, interface and type are mainly different

1 Type aliases can be used for other types (union type, tuple type, basic type (primitive value)), interface does not support

type PartialPointX = {
    
     x: number };
type PartialPointY = {
    
     y: number };

// union(联合)
type PartialPoint = PartialPointX | PartialPointY;

// tuple(元祖)
type Data = [PartialPointX, PartialPointY];

//primitive(原始值)
type Name = Number;

// typeof的返回值
let div = document.createElement('div');
type B = typeof div;

2 interface can be defined multiple times and is regarded as a combination of all declared members. The type is not supported

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

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

3 type can use in keyword to generate mapping type, but interface cannot.

type Keys = 'firstname' | 'surname';

type DudeType = {
    
    
  [key in Keys]: string;
};

const test: DudeType = {
    
    
  firstname: 'Pawel',
  surname: 'Grzybek',
};

4 The default export method is different

// inerface 支持同时声明,默认导出 而type必须先声明后导出
export default interface Config {
    
    
  name: string;
}
// 同一个js模块只能存在一个默认导出哦
 type Config2 = {
    
    name: string}
  export default Config2

Guess you like

Origin blog.csdn.net/glorydx/article/details/112625953