ts에서 인터페이스와 유형의 차이점

1. typeof의 유형 별칭은 공용체 유형, 튜플 유형, 기본 유형과 같은 다른 유형에 사용할 수 있으며 인터페이스는 함수, 객체 및 클래스 유형만 나타낼 수 있습니다.

// 基本类型

type person = string

// 联合类型

interface Dog {

 name: string;

}

interface Cat {

 age: number;

}

type animal = Dog | Cat

// 元组类型

interface Dog {

name: string;

}

interface Cat {

age: number;

}

type animal = [Dog, Cat]

2. type의 별칭은 여러 번 정의할 수 없으며 오류가 보고되고 인터페이스는 여러 번 정의할 수 있으며 병합된 것으로 간주됩니다.

// ok
  interface aaa {
    age: Number;
  }
  interface aaa {
    name: string;
  }

  export const bbb = (params: aaa) => {
    ...
  }

  bbb({name: 'mm', age: 27})  // age和name属性都要有,否则就会报错

// 不ok  
// eslint提示:标识符“aaa”重复。ts(2300)。Use an `interface` instead of a `type`.
  type aaa = string | number;
  type aaa = {x: number, y: number};  

3. type은 in 키워드를 사용할 수 있지만 interface는 사용할 수 없습니다.

type Keys = "firstName" | "lastName" ;

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

const test: DudeType = {
    firstName: 'Anna',
    lastName: 'LMY',
}

4. 기본 내보내기 방법이 다릅니다 Inerface는 동시 선언을 지원하며 기본적으로 내보내는 반면 type은 먼저 선언한 다음 내보내야 합니다.

// 默认导出 不一致
export default interface{
    name: string;
    age: number;
}

type personInfo = [string, number];
export default personInfo;

// 分别导出 一致
export interface{
    name: string;
    age: number;
}

export type sizeType = 'small' | 'middle' | 'large' | undefined;

5. 확장 방식이 다르고, extends로 인터페이스 확장, & 연산자로 타입 확장

// interface extends interface
interface Person {
  name: string
}
interface User extends Person {
  age: number
}

// interface extends type
type Person = {
  name: string
}
interface User extends Person {
  age: number
}

// type & type
type Person = {
   name: string
}
type User = Person & { age: number }

// type & interface
interface Person {
  name: string
}
type User = {age: number} & Person

6. type은 typeof를 사용하여 인스턴스 유형을 가져올 수 있습니다.

let div = document.createElement('div');

type B = typeof div

おすすめ

転載: blog.csdn.net/BUG_CONQUEROR_LI/article/details/128790037