Skip to content

Instantly share code, notes, and snippets.

@DublinCity
Last active July 13, 2022 01:12
Show Gist options
  • Save DublinCity/79868f3e7dd5282f354d69fa6ff915de to your computer and use it in GitHub Desktop.
Save DublinCity/79868f3e7dd5282f354d69fa6ff915de to your computer and use it in GitHub Desktop.
# Item3: 코드 생성과 타입이 관계없음을 이해하기

Item3: 코드 생성과 타입이 관계없음을 이해하기

타입스크립트 컴파일러의 역할

타입스크립트 컴파일러는 완벽히 독립적인 두가지 일을 한다.

  • 최신 타입스크립트/자바스크립트를 구버전의 자바스크립트로 트랜스 파일
  • 코드의 타입오류를 체크

따라서, 타입스크립트에서는 C나 Java와 다르게 타입오류가 있는 코드도 컴파일이 가능하다.

런타임에 타입정보를 유지하는 방법 3가지

타입은 런타임시점에 아무런 역할을 할 수 없다. 따라서 런타임에 접근가능한 체크를 통해서 타입을 유지할 수 있다.

속성을 체크하기

해당 속성이 있는지 체크하면 런타임에 타입을 좁힐 수 있다.

interface A {
    kind: 'Akind'
    name: string
}

interface B {
    kind: 'Bkind'
    age: number
}

const prop = (input: A|B) => {
    if('name' in input) {
        // input: A
        console.log(input.name)
    } else {
        // input: B
        console.log(input.age)
    }
}

태그된 유니온(tagged union)

만약 공통된 속성이 있다면 해당 속성을 체크하여 타입을 좁힐 수 있다.

// interface A, interface B 선언

const prop = (input: A|B) => {
    if(input.kind === 'Akind') {
        // input: A
        console.log(input.name)
    } else {
        // input: B
        console.log(input.age)
    }
}

// TS 4.6 버전부터는 Destructured 된 Union 도 타입 추론을 지원한다.
const prop = (input: A|B) => {
    const {kind} = input // Work after TS 4.6 version
    if(kind === 'Akind') {
        // input: A
        console.log(input.name)
    } else {
        // input: B
        console.log(input.age)
    }
}

런타임의 타입은 선언된 타입과 다를 수 있다

일반적으로 타입스크립트에서 죽은 코드를 찾아낼 수 있다. 하지만 아래같은 경우는 default 문이 필요할 수 있는데, 런타임의 타입은 선언된 타입과 다를 수 있기 때문이다. 예를들면 네트워크 호출로부터 받아온 값으로 함수를 실행하는 것이다.

// interface A, interface B 선언

const prop = (input: A|B) => {
    const {kind} = input // Work after TS 4.6 version
    switch(kind) {
        case 'Akind': // some code..
            break;
        case 'Bkind': // some code..
            break;
        default: // should default case need?
            console.log(input)
    }
}

const result = await fetchData() // network request
prop(result)

결론

  • 타입오류가 있어도 코드생성(컴파일)은 가능하다.
  • 런타임에 타입정보를 유지하려면 속성체크, 태그된 유니온, 클래스 체크를 사용한다.
  • 런타임에는 선언된 타입과 다를 수 있음을 이해하고 코드를 작성해야한다.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment