[typscript]: interface & Duck Typing

이홍경·2022년 1월 26일
0
post-thumbnail

interface란?

interface는 일반적으로 타입 체크를 위해 사용된다. 변수, 함수, 클래스에 사용할 수 있으며, 인터페이스에 선언된 속성 혹은 메소드의 구현을 강제하여 일관성을 유지할 수 있도록 하는 것이다. implements로 타입을 체크 할 수 있으며, interface에 정의한 속성들을 내부에 정의해 줘야 한다. 정의하지 않으면 에러가 발생한다.

interface Person {
  name: string;
  age: number;
  info(country: string): void
}

class AnotherPerson implements Person {
  name = '이차돌';
  age = 20;

  info(country: string) {
    console.log(`나는 ${country}${age}${name}이다!!`)
  }
}

const kor = new AnotherPerson();
console.log(kor.info('대한민국')) // 나는 대한민국의 20살 이차돌이다!!

위와 같이 정의 할때 interface에 정의한 내용을 지켜 작성해 줘야 한다.

Duck Typing이란???

Duck Typing이란 Duck Test에서 유래 되었다고 하며, 추론 방법 중 귀추법에 근거한 것이다. 일종의 프로그래밍 패턴이며, 정확하지는 않지만 단서를 보고 추론에 근거하는 것이다.

interface Say {
  say(): void;
}

class Duck implements Say {
  say() {
    console.log('꽉!');
  }
}

class Person {
  say() {
    console.log('뷁?!');
  }
}

function howToSay(anything: Say): void {
  anything.say();
}

howToSay(new Duck()); // 꽉!
howToSay(new Person()); // 뷁?!

class Person은 implements 하지 않았는데 왜 작동하는 것일까???
이렇게 타입스크립트에서는 interface의 메소드인 say()를 가지고 있는 것만으로 추론을 하는 것이고, 에러를 발생시키지 않는다. 이것이 Duck Typing이다.

profile
개발자를 꿈꾸는 자

0개의 댓글