TypeScript는 Structural Type System 을 따르고 있습니다.이름이 다르더라도 구조가 같으면, 같은 타입입니다.
TypeScript는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;
구조가 같아도 이름이 다르면, 다른 타입입니다.
이 구조를 가지고 있는 다른 언어에는
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'); // 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; }'.
만약 어떤 새가 오리처럼 걷고, 헤엄치고, 꽥꽥거리는 소리를 낸다면 나는 그 새를 오리라고 부를 것이다. 라는 철학을 가지고 타이핑 처리를 하는 것이 duck typing 입니다.duck typing은 duck testing 이라는 것에서 부터 유래가 되었습니다.Python 이 있습니다.Structural Type System 하고 유사한 방식이라고 생각할 수 있습니다.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)