TypeScript/Type System
TypeScript - Structural Type System VS Nominal Type System
KDONG
2022. 2. 7. 12:56
Structural Type System VS Nominal Type System
타입스크립트(Structural Type System)의 타입 체계를 이해하는데 도움이 되느 시스템이다.
interface IPerson {
name: string;
age: number;
speak(): string;
}
type PersonType = {
name: string;
age: number;
speak(): string;
};
let personInterface: IPerson = {} as any;
let personType: PersonType = {} as any;
personInterface = personType;
personType = personInterface;
Structural Type System
구조가 같으면, 같은 타입이다.
Nominal Type System
구조가 같아도 이름이 다르면, 다른 타입이다. (C언어, Java 등)
type PersonID = string & { readonly brand: unique symbol };
function PersonID(id: string): PersonID {
return id as PersonID;
}
function getPersonById(id: PersonID) {}
getPersonById(PersonID("id-aaaaaa"));
getPersonById("id-aaaaaa"); // Argument of type 'string' is not assignable to parameter of type 'PersonID'. Type 'string' is not assignable to type '{ readonly brand: unique symbol; }'.ts(2345)
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)
Notion : https://torpid-pasta-de7.notion.site/Type-System-d3622ddf91d647679417c9cbc2db947c