updated_at: 2025-03-07 17:07

Type Alias vs Interface

이전 장에 Type에 대해서 설명을 드렸습니다.
type은 number, string.. 등 일반적인 것들도 있지만 실제 프로그램에서는 사용자 정의를 하여 많이 사용합니다.
먼저 아래 예제를 보겠습니다.

Examples

Type Alias을 이용한 정의

type Prifile = {
name: string;
age: number;
}

const pondol: Prifile = {
name: 'Pondol',
age: 18
};

Interface를 이용한 정의

interface Prifile {
name: string;
age: number;
}

const pondol: Prifile = {
name: 'Pondol',
age: 18
};

Type Alias vs Interface

Type Alias Interface
정의
type TBase = {
  t: number;
};
interface IBase {
  i: number;
}
extends 사용 interface I1 extends TBase {} interface I2 extends IBase {}
implements 사용
class C1 implements TBase {
  constructor(public t: number) {}
}
class C2 implements IBase {
  constructor(public i: number) {}
}
곱 타입에 대한 extends, implements 사용
type TIntersection = TBase & {
  t2: number;
};

interface I3 extends TIntersection {}

class C3 implements TIntersection {
  constructor(public t: number, public t2: number) {}
}
interface I4 extends I3 {}

class C4 implements I3 {
constructor(public t: number, public t2: number) {}
}
합 타입에 대한 extends, implements 사용
type TUnion = TBase | {
  u: number;
};

interface I5 extends TUnion {}
// error(TS2312)
// An interface can only extend an object type
// or intersection of object types with statically known members.
type TUnion = TBase | {
  u: number;
};

class C5 implements TUnion {}
// error(TS2422)
// A class can only implement an object type
// or intersection of object types with statically known members.

다양한 예제

example 1

입력값이 object type으로 정의하고 및 출력 정의

interface Iparams {
  (options: {
    idx: number;
    bool: boolean;
    str: string;
  }): string;
}

export const pondol: Iparams =
  ({ idx, bool = true, str }): string => {
}
평점을 남겨주세요
평점 : 2.5
총 투표수 : 1

질문 및 답글

Copyright © 온스토리