ㅇㅇㅈ Blog

프론트엔드 수행중

0%

Structural Type System vs Nominal Type System

Structural Type System vs Nominal Type System

Structural Type System - 구조가 같으면, 같은 타입이다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface Iperson {
name: string
age: number
speak(): string;
}

type PersonType = {
name: string
age: number
speak(): string;
}
// Iperson 과 PersonType은 똑같은 구조다

let personInterFace: IPerson = {} as any
let personType: PersonType = {} as any

personInterface = personType;
personType = personInterface

nominal type system - 구조가 같아도 이름이 다르면, 다른 타입이다

  • nominal type system은 타입스크립트는 따르지 않는다
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    type PersonID = string  & { readonly brand: unique symbol}

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

    function getPersonById(id: PersonID){}

    getPersonbyId(personId('id-aaaa'))
    getPersonbyId(('id-aaaa')) // 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}'