Typescriptテンプレート文字列タイプ

テンプレート文字列メカニズムを使用して文字列タイプを絞り込む方法

テンプレートリテラルタイプとは

Typescript 4.1以降、文字列の入力を大幅に強化できます。簡単に要約すると、Typescriptではいわゆる「リテラルタイプ」を定義できます。変数を文字列として定義するだけでなく、許可されている特定の文字列のセットに型を絞り込むことができます。

// Define a mutable string as 'Literal Type'.
let key: "name" | "department" = "name";

// This works, as 'department' is part of the type.
key = "department";
// Won't work, as it's not define in the union type.
key = "company";

// Of course, the same applies for functions.
function getKey(): "name" | "department" {
  return Math.random() <= 0.5 ? "name" : "department";
}

Typescript 4.1以降、この概念はさらに発展してきました。 Javascriptの「TemplateLiteralStrings」をインスピレーションとして取り入れることで、Typescriptのリテラルタイプに同じ構文を適用できます。主な違いは、「テンプレートリテラルタイプ」では、タイプ自体がこの形状のパラメーターを受け取ることができるため、柔軟性が大幅に向上することです。概念はジェネリックに似ていますが、特定の値が必要であるという点でわずかに異なります。

// Define a Literal Type
type State = "ready";

// Nice, isn't it? As in Javascript's 
// 'template literal strings', we can
// reuse the same syntax for TS.
//
// The create type here is now 'Key-ready'.
type Key = `key-${State}`;
// This of course works for union types as well.
// Let's take these non-descriptive types for a 
// quick demo:
type GraphState = "sleep" | "ready" | "error";
type MachineState = "booting" | "running";

// And here's the 'template literal type':
type EntityState = `ES-${GraphState | MachineState}`;

// The possible combinations therefore 
// work out like this:
//
// type EntityState = 'ES-sleep' 
//  | 'ES-ready'
//  | 'ES-error'
//  | 'ES-booting'
//  | 'ES-running'

Typescript4.3にはさらに多くのものがあります

これを書いているときに、Typescript 4.3のリリース候補がリリースされました。これには、テンプレートリテラルタイプのさらなる機能強化が含まれています。

型システムはさらに動的になり、正しい型をより適切に推測できるようになりました。これらの最新の変更により、テンプレート文字列タイプがさらに成熟します。

// This example is taken 1:1 from 
// Typescript's 4.3 announcement.
// Please check out the link in the
// addendum to see all examples!

declare let s: string;
declare function f<T extends string>(x: T): T;

// Previously: string
// Now       : `hello-${string}`
let x2 = f(`hello ${s}`);

結論

ご覧のとおり、Typescriptは、動的型の定義に関しては非常に強力な言語です。これは、文字列ベースのタイプに特に当てはまります。バージョン4.3の最新の変更により、型システムはこれまで以上に正しい型を推測できるようになり、Typescriptでの作業が楽しくなりました。

提案

関連する

追加事項

言語