Computer Science/TypeScript

Template Literal Type

imygnam 2023. 10. 14. 15:54

1. Template Literal Type

2. Base 형태

3. Uniton Type을 이용한 Template Literal Type

4. 여러개의 Union Type을 이용한 Template Literal Type

5. Conditional Type을 같이 사용하여 추론하기

6. 공백 제거 및 특정 형태 쪼개기

7. 기타

8. 참조


1. Template Literal Type이란?

String Literal Type을 기반으로 새로운 타입을 만드는 도구

 

2. Base 형태

type Champion = 'Malphite';

type ChampionLane = `${Champion} Top`;

위와 같이 한다면 string으로 Malphite Top을 만들 수 있는 Type을 생성한다.

 

3. Union Type을 이용한 Template Literal Type

type Champion = 'Malphite';
type Lane = 'Top' | 'Mid' | 'Bottom'

type ChampionLane = `${Champion} ${Lane}`;

위와 같다면 Malphite Top, Malphite Mid, Malphite Bottom이 가능한 Type을 생성한다.

 

4. 여러개의 Union Type을 이용한 조합

type Champion = 'Malphite' | 'Maokai';
type Lane = 'Top' | 'Mid' | 'Bottom'

type ChampionLane = `${Champion} ${Lane}`;

위와 같이 조합형태로도 사용이 가능하다.

 

5. Conditional Type을 같이 사용하여 추론하기

type WhatLane<T> = T extends `Malphite ${infer R}` ? R : never;

type Top = WhatLane<"Malphite Top">

위와 같이 사용한다면 Top만 꺼내서 사용이 가능하다.

 

6. 공백 제거 및 특정 형태 Splite

type Right<T extends string> =
  if (T extends `${infer R} `) {
    return Right<R>;
  } else {
    return T;
  }
// typeNospace = "test"
type NoSpace = Right<"test    ">;


type Split<S extends string> =
  S extends `${infer T}.${infer U}`
    ? [T, ...Split<U>]
    : [S];

// type S = ["foo", "bar", "baz"];
type S = Split<"foo.bar.baz">;

위와 같이 재귀적 타입 정의를 활용하여 공백을 제거하거나 특정형태의 문자를 쪼갤수 있다.

 

7. 기타

documet.queySelector를 안전하게 사용할 수 있다.

declare function querySelector<T extends string>(query: T): QueryResult<T>;

const a = querySelector('div.banner > a.call-to-action'); //-> HTMLAnchorElement
const b = querySelector('input, div'); //-> HTMLInputElement | HTMLDivElement
const c = querySelector('circle[cx="150"]') //-> SVGCircleElement
const d = querySelector('button#buy-now'); //-> HTMLButtonElement
const e = querySelector('section p:first-of-type'); //-> HTMLParagraphElement

https://twitter.com/MikeRyanDev/status/130847227901002547

 

8. 참조

https://toss.tech/article/template-literal-types

 

Template Literal Types로 타입 안전하게 코딩하기

TypeScript 코드베이스의 타입 안전성을 한 단계 올려줄 수 있는 Template Literal Type의 뜻과 응용에 대해 알아봅니다.

toss.tech

 

https://github.com/ghoullier/awesome-template-literal-types

 

GitHub - ghoullier/awesome-template-literal-types: Curated list of awesome Template Literal Types examples

Curated list of awesome Template Literal Types examples - GitHub - ghoullier/awesome-template-literal-types: Curated list of awesome Template Literal Types examples

github.com