• Home
  • About
    • lahuman photo

      lahuman

      열심히 사는 아저씨

    • Learn More
    • Facebook
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

typescript에서의 class, interface 그리고 duck type

07 Sep 2023

Reading time ~1 minute

typescript에서의 duck typing?

다음 코드가 타입스크립트에서도 안될꺼라 생각했다.

class CatInfo {
  age: number;
  breed: string;
  constructor(age: number) {
    this.age = age;
    this.breed = "C1";
  }
}
class CatInfo2 {
  age: number;
  breed: string;
  constructor(age: number) {
    this.age = age;
    this.breed = "C2";
  }
}
let c1:CatInfo = new CatInfo(10);
let c2:CatInfo2 = new CatInfo2(6)
function hello(c: CatInfo) {
  console.log(c instanceof CatInfo)
  console.log(c);
}
hello(c2);

하지만 잘된다. 몰랐다.

위와 같이 구조가 같으면 같은 타입이라고 간주하는 방식을 Structural Typing하고, 이름 또는 hashCode 등으로 구분하는 방식을 Nominal Typing 라고 합니다.

typescript에서 Nominal Typing 방식을 사용하고 싶다면,다음과 같이 트릭을 이용할 수 있습니다.

class CatInfo {
  private age: number;
  private breed: string;
  constructor(age: number) {
    this.age = age;
    this.breed = "C1";
  }
}
class CatInfo2 {
  private age: number;
  private breed: string;
  constructor(age: number) {
    this.age = age;
    this.breed = "C2";
  }
}
let c1:CatInfo = new CatInfo(10);
let c2:CatInfo2 = new CatInfo2(6)
function hello(c: CatInfo) {
  console.log(c instanceof CatInfo)
  console.log(c);
}
hello(c2); // error

property 항목 중 한개라도 private으로 선언하면 Nominal Typing 방식처럼 동작 합니다.

다른 방법도 Nominal typing techniques in TypeScript 를 참조하면 보여집니다

정리

  • Duck Typing : 런타입 시점에 객체의 변수 및 메소드의 집합이 객체의 타입을 결정
  • Structural Typing : 컴파일 시점에 Duck Typing 와 같이 객체의 구조로 객체의 타입을 결정
  • Nominal Typing : 클래스의 이름 또는 hashCode 등으로 객체의 타입을 결정

javascript에서는 Duck Typing을 지원하고, typescript에서는 Structural Typing 지원합니다. 둘의 차이는 어느 타이밍에 객체의 타입을 결정하는지에 따라 다를뿐 동작은 동일합니다.

또한, Typescript는 Structural Typing을 지원하지만, 몇가지 트릭을 이용하면, Nominal Typing과 같이 사용이 가능하다.

잘 알고 쓰자!!!

참고자료

  • TypeScript와 Duck Typing의 관계 쉽게 설명하기
  • Nominal typing techniques in TypeScript
  • TypeScript 타입 시스템 뜯어보기: 타입 호환성


typescript Share Tweet +1