[Typescript]Structural Type System vs Nominal type System

rondido·2023년 2월 23일
0

Typescript

목록 보기
5/6

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;

Nominal type System - 구조가 같아도 이름이 다르면, 다른 타입이다. (c 언어, 자바)

type PersonID = string & {readonly brand:unique symbol};

function PersonID(id:string):PersonID{
	return id as PersonID;
}

function getPersonById(id:PersonID){}

getPersonById(id:PersonID('id-aaaaaa'));
getPersonById(('id-aaaaaa')); //error

duck typing(typescript x)

만약 어떤 새가 오리처럼 걷고, 헤엄치고, 꽥꽥거리는 소리를 낸다면 나는 그 새를 오리라고 부를 것이다.

profile
개발 옆차기

0개의 댓글