공부/TypeScript
TypeScript - Structural Type System VS Nominal Type System
도리암
2022. 2. 27. 20:32
Structural Type System vs Nominal Type System
structural type system - 구조가 같으면 같은 타입
- Duck typing, Structural typing이라고도 불린다.
- 서로 다른 타입이더라도 필요한 프로퍼티만 있으면 할당이 가능하다.
- 프로퍼티의 순서가 달라도, 추가로 다른 프로퍼티가 있어도 문제없다.
interface foo { name: string, };
let bar = {
name: 'hello',
age: 10,
};
let f: foo = bar; // OK
console.log(f) // { name: 'hello', age: 10 }
## nominal type system - 구조가 같아도 이름이 다르면 다른 타입.
```js
type PersonID = string & { readonly brand: unique symbol };
// string에 객체를 intersection한 것.
function PersonID(id: string): PersonID {
return id as PersonID;
} // string을 받아 PersonID라는 형식으로 변환해주는 함수.
function getPersonById(id: PersonID) {} // PersonID형식만 받을 수 있다.
getPersonById(PersonID('id-aaaaaa'));
getPersonById('id-aaaaaa'); // 일반 string형식은 타입이 달라 받을 수 없다.
// error TS2345: Argument of type 'string' is not assignable to parameter of type 'PersonID'. Type 'string' is not assignable to type '{ readonly brand: unique symbol;}'.
타입스크립트는 기본적으로 nominal 타입 시스템을 따르지 않는다.
위의 예제는 nominal type을 따르도록 하는 예제임.
duck typing
- 만약 어떤 새가 오리처럼 걷고, 헤엄치고, 꽥꽥거린다면 나는 그것을 오리라고 부를 것이다.
- 런타임에 발생하는 타이핑 방식
- 파이썬에서 주로 사용됨.
- 타입스크립트엔 존재하지 않는다.
class Duck: def sound(self): print u"꽥꽥"
class Dog:
def sound(self):
print u"멍멍"
def get_sound(animal):
animal.sound()
def main():
bird = Duck()
dog = Dog()
get_sound(bird)
get_sound(dog)
```