目次 (10)
[Typescript] Template Literal Types
TypeScriptの機能を1つずつ取り上げていく予定です。その最初の機能に選ばれたのはTemplate Literal Typesです。literal types自体は難しい内容ではありませんが、2.活用例はGeneric TypeとType inferについて知っていないと理解しにくいと思います。
1. Literal型とTemplate Literal型
Template Literal型とは、文字列リテラルをテンプレート文字列の形式(バッククォート ``)で作り、組み合わせて使えるようにしてくれる型です。
Template Literal型とString Literal型は、文字列の規則に従ったデザイントークンの生成や、Objectのkey値に応じた型の自動生成など、さまざまな状況で使えます。以下はそれぞれの型についての説明です。
Literal Type : string、numberのような一般的な型だけでなく、特定の文字列や数値を型として指定した型です。
type Direction = "left" | "right";const direction:Direction = "left"; ✅const direction:Direction = "up"; ❌ // leftとrightの値しか持てない。Type '"up"' is not assignable to type '"left" | "right"'const direction:string = "up"; ✅ // string型はあらゆる文字列が可能だ。Template Literal : String Literalをテンプレート文字列の形式(バッククォート ``)で組み合わせて作る型です。
type Fruit = "apple" | "banana" | "mango";type Sentence = `I like ${Fruit}`;const sentence:Sentence = "I like apple"; ✅const sentence:Sentence = "I hate apple"; ❌ // I like ではない。Type '"I hate apple"' is not assignable to type '"I like apple" | "I like banana" | "I like mango"'.const sentence:Sentence = "I like melon"; ❌ // Fruit型にない果物だ。Type '"I like melon"' is not assignable to type '"I like apple" | "I like banana" | "I like mango"'.2. Template Literalの活用例
Template Literalをどんな状況で使えるのか、例でお見せします。私がTemplate Literalを使った例を1つと、公式ドキュメントの活用例を1つ持ってきました。
2.1 デザイントークン - Typography
私はこの機能を、デザインシステムで{type}-{Size}-{Weight}の規則を持つTypographyデザイントークンを定義するのに活用していました。以下がそのサンプルコードです。
type FontType = "title" | "body";type FontSize = "sm" | "md" | "lg";type FontWeight = "regular" | "medium" | "bold";type FontVariant = `${FontType}-${FontSize}-${FontWeight}`; // FontType 2種類 FontSize 3種類 * FontWeight 3種類 = 18種類;// "title-sm-regular", "title-md-regular", "title-md-bold", "title-md-regular...など18種類の文字列ユニオン型が作られます。type FontProperties = Pick< CSSProperties, "fontWeight" | "lineHeight" | "fontSize" | "letterSpacing">;type Typography = Record<FontVariant, FontProperties>;const typography: Typography = { "body-lg-bold": { fontSize: "1rem", fontWeight: 700, letterSpacing: 0, lineHeight: 1, }, "body-lg-medium": { fontSize: "1rem", fontWeight: 500, letterSpacing: 0, lineHeight: 1, }, //...};もしTypography型をもっと厳密に適用したいなら、応用することもできます。次は、FontWeightに応じてCSSのfontWeight型が自動的に固定される例です。
import {CSSProperties} from "react";type FontType = "title" | "body";type FontSize = "sm" | "md" | "lg";type FontWeightValueMap = { regular: 400; medium: 500; bold: 700;};// もし変数としても使いたいなら、const fontWeightValueMapとして変数を作って使う。typeof指示子で型を呼び出す。type FontWeight = keyof FontWeightValueMap; // "regular" | "medium" | "bold"type FontWeightCSSProperty<FW extends FontWeight> = { fontWeight: FontWeightValueMap[FW];}; //FontWeightに応じて値をCSSのliteral type numberに固定。type FontVariant = `${FontType}-${FontSize}-${FontWeight}`; // 18種類のトークンtype ExtractFontWeight<FV extends FontVariant> = FV extends `${string}-${string}-${infer FW}` ? FW : never; // FontVariantからFontWeightを抽出type FontProperties<FV extends FontVariant> = Pick< CSSProperties, "lineHeight" | "fontSize" | "letterSpacing"> & FontWeightCSSProperty<ExtractFontWeight<FV>>; //fontWeightはFont VariantのFont Weightに応じて値が決まる。type Typography = { [key in FontVariant]: FontProperties<key>;};const typography: Typography = { "body-lg-bold": { fontSize: "1rem", fontWeight: 700, ✅ letterSpacing: 0, lineHeight: 1, }, "body-lg-medium": { fontSize: "1rem", fontWeight: 700, ❌ mediumは500の値を持たなければならないため型エラー。Type '700' is not assignable to type '500' letterSpacing: 0, lineHeight: 1, }, //...};デザインシステムで2つの型設定方法のうちどちらが良いかと聞かれたら、どんな利点を得たいか、あるいは状況によって異なります。デザイントークンの構造をこれ以上触る予定もない、あるいは素早く終わらせるプロジェクトなら、型に気を配るのは時間の無駄にしかなりません。しかし、重要な位置づけで使うデザインシステムとしてFigmaまで連携し、バージョン管理やFigmaへの自動反映まで考慮しているなら、明確なデザイン企画に沿って型を設定するほうが良さそうです。結論として、私の考えでは、使える人員、熟練度、時間の余裕など、状況に応じて決めるのが良いと思います。
2.2 公式ドキュメントの例
以下は、公式ドキュメントにある、objectのliteralなキー値とそのvalueの型に応じて関数の型が自動的に作られる例です。objectのvalueの型がさまざまでも、開発者はマッチした型で楽にコーディングできます。
type PropEventSource<T> = { on<Key extends string & keyof T> (eventName: `${Key}Changed`, callback: (newValue: T[Key]) => void): void;};// ${Tのkey値} + "Changed"がeventNameになる。callbackのnewValueは${Tのkey値にマッチするvalueの型になる}/// Create a "watched object" with an `on` method/// so that you can watch for changes to properties.declare function makeWatchedObject<T>(obj: T): Type & PropEventSource<T>;const person = makeWatchedObject({ firstName: "Saoirse", lastName: "Ronan", age: 26});person.on("firstNameChanged", (newName) => {console.log(newName)});// on関数の1番目のパラメータは`{key}Changed`になり、2番目のパラメータの関数のnewNameは自動的にstring型になる。 person.on("ageChanged", newAge => {console.log(newAge)})// 同様に、${personのkey値 = "age"}+"Changed"、newAgeはperson["age"]の型だ。3. 関連するユーティリティ型
以下は、Template Literal、String Literalに関連するユーティリティ型です。公式ドキュメントから持ってきました。
3.1 Uppercase
すべての文字を大文字の型に変換してくれるユーティリティ。
type Greeting = "Hello, world"type ShoutyGreeting = Uppercase<Greeting> // "HELLO, WORLD" 型type ASCIICacheKey<Str extends string> = `ID-${Uppercase<Str>}`type MainID = ASCIICacheKey<"my_app"> // "ID-MY_APP" 型3.2 Lowercase
すべての文字を小文字の型に変換してくれるユーティリティ。
type Greeting = "Hello, world"type QuietGreeting = Lowercase<Greeting> // "hello, world" 型type ASCIICacheKey<Str extends string> = `id-${Lowercase<Str>}`type MainID = ASCIICacheKey<"MY_APP"> // "id-my_app" 型3.3 Capitalize
最初の文字を大文字の型に変換してくれるユーティリティ。
type Greeting = "hello, world"type ShoutyGreeting = Uppercase<Greeting> // "Hello, world" 型3.4 Uncapitalize
最初の文字を小文字の型に変換してくれるユーティリティ
type Greeting = "HELLO WORLD"type ShoutyGreeting = Uppercase<Greeting> // "hELLO WORLD" 型