TypeScript, 읽기전용 튜플로부터 유니온 문자열 타입 얻기

대부분의 메타 프로그래밍에서처럼 TypeScript 역시 짧은 코드에 함축된 다양한 내재 기능이 적용되어 개발자에게 혼란스러움을 주는 경우가 많습니다. 아래의 코드가 그 예시인데요.

const methods = [
    "GET",
    "POST",
    "PUT",
    "DELETE"
] as const;

type Method = typeof methods[number];

위의 타입으로써 Method는 다음과 같습니다.

"GET" | "POST" | "PUT" | "DELETE"

여기에 적용된 TypeScript와 관련된 적용 기능 중 중요한 것을 2가지 뽑지면 as const를 통한 문자열 배열의 ‘읽기전용 튜플화’와 Indexed Access Type을 통한 ‘유니온 타입화’입니다.

TypeScript, 익명 클래스

타입스크립트, 정확히는 JavaScript도 익명 클래스를 정의할 수 있습니다. 다음처럼요.

const x = new class<Type> {
  content: Type;
  constructor(value: Type) {
    this.content = value;
  }

  say() {
    console.log(this.content);
  }
}("Hello World!");

x.say();

TypeScript, this 라는 타입에 관하여

타입스크립트에서는 클래스에서 사용되는 this라는 타입이 있습니다. 이 this 타입은 동적으로 현재 클래스에 대한 타입으로 결정됩니다. 애매하고 어렵죠? 예시를 통해 좀더 살펴보면..

class Box {
  content: string = "";
  sameAs(other: this) {
    return other.content === this.content;
  }
}
 
class DerivedBox1 extends Box {
  otherContent: string = "?";
}

class DerivedBox2 extends Box {
  otherContent: string = "?";
}
 
const base = new Box();
const derived1 = new DerivedBox1();
derived1.sameAs(base);

const derived2 = new DerivedBox2();
derived2.sameAs(base);

위의 코드에서 Box 클래스의 sameAs 인자의 other 타입이 this입니다. 이 Box 클래스를 상속받는 파생클래스들을 통해 sameAs를 사용할 경우 sameAs의 첫번째 인자인 other는 각 파생클래스의 타입이 됩니다. 즉 derived1sameAs 매서드의 정의는 다음과 같고…

sameAs(other: DerivedBox1): boolean

derived2sameAs 매서드의 정의는 다음과 같습니다.

sameAs(other: DerivedBox2): boolean

TypeScript, 같은 타입이지만 다른 타입으로 만드는 방법(Branding)

Branding은 타입스크립트 고유 문법이 아닌 응용입니다. 브랜딩을 위해서는 먼저 다음과 같은 코드가 필요합니다.

type Brand<T, B extends string> =
    T & { readonly __brand: B };

위의 타입 정의를 통해 string 타입이지만 다른 용도로 정의할 수 있습니다. (브랜딩 화)

type UserId = Brand<string, "UserId">;
type PostId = Brand<string, "PostId">;

UserIdPostIdstring 타입이지만 이 둘은 서로 다른 타입입니다. 만약 다음과 같은 함수가 있다면..

function getPost(userId: UserId, postId: PostId) {
    // ...
}

위의 함수는 반드시 다음처럼 사용해야 합니다.

const userId = "hjkim" as UserId;
const postId = "3434" as PostId;

getPost(userId, postId); // ✅
// getPost(postId, userId); // ❌

참고로 Brand의 두번째 제네릭 타입 인자로 전달되는 문자열 타입이 저장되는 __brand는 타입 정보일뿐이므로 Javascript 단에서는 존재하지 않습니다.

TypeScript, Mapped Types

다음과 같은 타입이 있습니다.

type T = {
  id: string;
  postId: string;
}

위의 타입을 구성하는 키들은 "id" | "postId"인데, 이 키들로 구성된 타입은 다음 코드로 얻을 수 있습니다.

type KEYS = keyof T;

다음의 코드를 통해 T 타입을 구성하는 키들의 타입을 number로 변경할 수 있습니다.

type X = { [K in KEYS]: number };
// type X = { [K in "postId" | "useId"]: number };

즉, 위의 타입 결과는 다음과 같습니다.

type X = {
 id: number;
 postId: number;
}

Mapped Types를 이용해 각 키와 값에 대한 readonly 또는 optional로 변경할 수 있습니다.

type readonly_X = { +readonly [K in KEYS]: number };
type optional_X = { [K in KEYS]+?: number };

readonly? 앞에 + 또는 -를 지정함으로써 readonly와 optioanl을 지정할지(+) 제거할지(-)를 결정할 수 있습니다. 이 +-를 지정하지 않으면 +가 지정된 것으로 판단합니다.