공부/TypeScript

Type Script - Type Alias, Interface

도리암 2022. 2. 27. 20:34

type alias vs interface

type aliase

  • interface와 유사하게 사용 가능.
  • Primitive, Union Type, Tuple, Function에 사용 가능.
  • 기타 직접 작성해야하는 타입을 다른 이름을 지정할 수 있다.
  • 만들어진 타입의 refer로 사용하는 것이지 타입을 만드는 것은 아님.
  • 다른 대상을 가리키거나 별명으로서 존재한다.
  • OR 표현이 가능하다.

interface

  • 타입을 직접 만들어 내는 명령어
  • JavaScript에서는 사용할 수 없다. (존재하지 않음)
  • 보통 class의 내부 프로퍼티를 감추는 용도로 사용한다.
  • 타입으로서의 목적이나 존재가치가 명확하다.

예시

Tuple

// type alias
type tuple = [number, string];
let tu:tuple = [1, "string"];
console.log(tu) // [1, "string"]

// Interface
interface inter {
  int_tu : [number, string],
  int_str : string
}
let int:inter = {"int_tu":[2, "interface"],  int_str: "try1"};
console.log(int) // { int_tu: [ 2, 'interface' ], e: 'try1' }

int = {int_tu:[3,"interface2"],int_str: "try2"}
console.log(int) // { int_tu: [ 3, 'interface2' ], e: 'try2' }
console.log(int.int_tu) // [ 3, 'interface2' ]

Function

// type alias
type EatType = (food: string) => void;

// interface
interface IEat {
  (food: string): void;
}

Array

// type alias
type PersonList = string[];

// interface
interface IPersonList {
  [index: number]: string;
}

Intersection (교집합)

interface ErrorHandling {
  success: boolean;
  error?: { message: string };
}

interface ArtistsData {
  artists: {name: string} [];
}

// type alias
type ArtistsResponseType = ArtistsData & ErrorHandling;

// interface
interface IArtistsResponse extends ArtistsData, ErrorHandling {}

let art: ArtistsResponseType;
let iar: IArtistsResponse;

Union Types (합집합)

Interface는 or 표현이 불가능하다.
Bird 또는 Fish라는 표현을 사용하고 싶으면 Type Alias를 사용해야 한다.

interface Bird {
  fly(): void;
  layEggs(): void;
}

interface Fish {
  swim(): void;
  layEggs() : void;
}

// type alias
type PetType = Bird | Fish;

// 알리아스는 or 표현이 되지만 인터페이스나 클래스는 or 표현을 할 수 없다.

// interface
interface IPet extends PetType {}
// error TS2312: An interface can only extend an object type or intersection of object types with statically known members.

class Pet implements PetType {}
// error TS2422: A class can only implement an object type or intersection of object types with statically known members.

Declaration Merging

Type Alias에서는 불가능하다. (중복 선언 불가능)
선언을 두번 하게 되면 두 선언이 합쳐지는 결과가 나타남.

interface MergingInterface {
  a: string;
}
interface MergingInterface {
  b: string;
} // 선언이 merging 됨.

let mi: MergingInterface;