Typescript 4. Generic

Alpha, Orderly·2023년 1월 9일
0

typescript & javascript

목록 보기
4/6
post-thumbnail

Generic

자바의 제네릭 문법과 매우 유사합니다.

제네릭 함수

function add<T> (a: T, b: T) {
    if (typeof a === 'number' && typeof b === 'number') {
        console.log(a + b)
    } else {
        console.log(a, b)
    }
}

T가 어떤 타입이 될지 모르기에 Type guard가 필요합니다.

과 같이 number이거나 number를 상속받은 자식 클래스로 한정하면

타입체크가 필요하지 않게 될수도 있습니다.

제네릭 클래스

class Example<T> {
    lst: Array<T> = [];
}

keyof

let obj = { a: 1, b: 2, c: 3 };

라는 객체에 대해

keyof obj는 "a" | "b" | "c" 와 같은 obj의 키값들의 리터럴 유니온 타입이 됩니다.

A extends keyof obj 와 같이 사용시 A 타입은 "a" 나 "b" 나 "c"만 올수 있게 됩니다.

profile
만능 컴덕후 겸 번지 팬

0개의 댓글