가끔 Generic이 너무 고통스러울 때는 this가 희망이 된다.

SSEN
SSEN
Nov 1 · 3 min read

Generic이 여러 구조적 형태로 얽히기 시작하면 뇌정지가 올때가 있다.

Generic<T> 를 던져서 그 Generic<T>를 다시 재활용하는 경우, 머리통이 뽑힐 것 같이 지끈거릴때가 있는데…

가끔 Generic 선언의 연쇄가 너무 힘들다 싶으면 this로 뭉개는 것도 좋은 방법이다.

interface X {
labelFunction?: ((me: X) => string) | string;
}
interface X1 extends X {
foo: number;
}
const x: X1 = {
foo: 30,
labelFunction: ({foo}) => foo.toString(),
}

위와 같은 경우 ({foo}) 부분이 에러가 된다.

이걸 처리하겠다고 Generic을 사용하면

type X<T> = {
labelFunction?: ((me: X<T>) => string) | string;
}
interface X1 {
foo: number;
}
const x: X<X1> = {
foo: 30,
labelFunction: ({foo}) => foo.toString(),
}

이렇게 돌아가기는 하겠지만… 저놈의 Generic 선언에 따른 과부하를 감당하기 어렵게 되어버린다. 여기저기 Generic을 죄다 넣다보면 현타가 오게 된달까…

Generic이 유연성을 확보하는데 도움이 되긴 하지만… Type 구조를 어렵게 만드는 가장 큰 요인이 되기도 하기 때문에 상속으로 처리할 수 있는 것이라면 상속으로 처리하는게 더 좋긴 하다.

interface X {
labelFunction?: ((me: this) => string) | string;
}
interface X1 extends X {
foo: number;
}
const x: X1 = {
foo: 30,
labelFunction: ({foo}) => foo.toString(),
}

위와 같이 Type 내부에서 this 를 사용하는 경우 ({foo}) 부분이 에러로 처리되지 않는다.

복합적인 구조의 Union Type을 다루는 경우, Generic을 통해서 X<T> 형태로 X & T의 합성을 표현해야 할때도 있지만, this 를 적절히 활용한다면 T extends X 형태로 좀 더 단순한 운용을 할 수 있는 여지가 생기기도 한다.

interface X {
labelFunction?: ((me: this) => string) | string;
}
function useX<T extends X>(x: T): T {
}
interface Y extends X {
foo: number;
}
const y: Y = {
foo: 30,
labelFunction: ({foo}) => foo.toString(),
}
const y1: Y = useX(y)

this를 통해서 Type을 다루는 경우, 해당 Type을 다루는 Function 또는 Class를 설계할때 Generic<T extends X> 가 도움이 되기도 한다. Function 내부적으로 X에 해당하는 값들만 다루면서, 동시에 Return Type을 상속된 T로 보내겠다하는 경우 사용할만하다.

어우… Library의 Model Type을 다루는데, 해당 Model Type이 너무 다양한 형태로 확장되다보니 Generic 처리가 정말 무지갯빛으로 토할 것 같았다. thisT extends X 를 적절히 활용하면서 복잡도를 조금씩 줄여보는 중이다.

    Written by

    SSEN

    https://github.com/iamssen

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade