Type System - Structural Type System vs Nominal Type System

lbr·2022년 7월 15일

Structural Type System vs Nominal Type System

  • 이런것을 아는 것은 타입스크립트의 타입 체계를 이해하는데 도움이 됩니다.
  • TypeScriptStructural Type System 을 따르고 있습니다.

Structural Type System

이름이 다르더라도 구조가 같으면, 같은 타입입니다.

TypeScriptStructural 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;
  • 이름이 달라도 구조가 같으면 같은 타입이기 때문에 서로 대입이 가능합니다.

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'); // 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 입니다.
  • runtime에 발생하는 typing방식입니다.
  • duck typingduck 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)
profile
ro

0개의 댓글