-
typescript에서의 class, interface 그리고 duck typeNodeJS 2024. 6. 27. 17:22728x90
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과 같이 사용이 가능하다.
잘 알고 쓰자!!!
참고자료
728x90'NodeJS' 카테고리의 다른 글
Typescript에서 특정 key를 가진 타입 생성 (0) 2024.06.25 nestjs에서 guard에 Global service Inject 처리 (0) 2024.06.20 [Nestjs TIP] whitelist 사용시 주의점! (0) 2024.06.18 [Nestjs TIP] Request Header에 validate 처리 (0) 2024.06.17 nestjs에서 registerAsync 사용시 isGlobal 설정 (0) 2024.06.12