Front/typescript

인터페이스

akii 2023. 8. 23. 15:41
인터페이스 : 타입에 이름을 지어주는 또 다른 문법, 객체의 구조를 정의하는데 특화
interface Person {
  readonly name: string;  // 읽기 전용 프로퍼티
  age?: number;           // 선택적 프로퍼티
  
  sayHi: () => void;      // 메서드 타입 정의 (함수타입 표현식)
  sayHi: (a: number, b: number) => void;  // ❌ 메서드의 오버로딩 구현이 불가
  
  sayHi(): void;          // 메서드 타입 정의 (호출 시그니처)     
  sayHi(a: number, b: number): void;
} | number // ❌ Union, Intersection 타입 정의 

type Type1 = number | string | Person;
type Type2 = number & string & Person;

const person: Person = {
  name: "이해찬",
  sayHi: function () {
    console.log("HI");
  },
};

// 하이브리드 타입
interface Func2 {
  (a: number): string;
  b: boolean;
}

const func: Func2 = (a) => "hello";
func.b = true;

person.sayHi();
person.sayHi(1, 2);

 

인터페이스 확장
: 상속, extends를 이용해서 다른 인터페이스로 부터 해당 인터페이스가 가지고 있는 모든 프로퍼티들은 자동으로 다 포함하도록 해줌
interface Nct {  // 슈퍼타입
  name: string;
  color: string;
}

interface NctDream extends Nct {
  //name: "hello";     // 타입 재정의 가능 -> string 리터럴 타입
  isCute: boolean;
}

const dream: NctDream = {
  name: "",
  color: "",
  isCute: true,
};

interface Nct127 extends Nct {
  isTall: boolean;
}

interface WayV extends Nct {
  isChinese: boolean;
}

// 다중확장 가능
interface NctU extends NctDream, Nct127 {}

const nctU: NctU = {
  name: "",
  color: "",
  isCute: true,
  isTall: true,
};

** 상속받는 인터페이스에서 동일한 프러퍼티의 타입을 다시 정의 가능(원본타입의 서브타입이여야 함)

 

선언 합치기(Declaration Merging) : interface는 별칭과 달리 동일한 이름 중복 가능 -> 중복된 선언 모두 합쳐짐
interface Person {
  name: string;
}

interface Person {
  //name: string; -> 충돌 허용 ❌
  age: number;
}

interface Developer extends Person {
  name: "hello";
}

const person: Person = {
  name: "",
  age: 24,
};

// 모듈 보강
interface Lib {
  a: number;
  b: number;
}

interface Lib {  // 선언 합침
  c: string;
}

const lib: Lib = {
  a: 1,
  b: 2,
  c: "hello",  // 추가
};