🌱

TypeScriptのリテラル型を知ろう

に公開

概要

別記事を書くにあたりリテラル型を理解しようの会

リテラル型とは

特定のものだけを許容する型
参考: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types

let s: string = "hello";
let h: "hello" = "hello";
s = "Hello"; // ✅代入できる
h = "Hello"; // 🚫代入できない

と書いたらsは文字列全て代入できるがhは"hello"しか代入できない。

let e: "hello" | "world" = "hello";
let l: [1, 2, 3] = [1, 2, 3];

e = "world"; // これは代入できる
l.push(4); // これはできない

また、constで定義された定数の一部についてはリテラル型になる。

const hoge = "ほげほげ";
type Hoge = typeof hoge; // リテラル型 "ほげほげ" になる

リテラル型は「特定の文字列」や「特定の配列」などを指定しているため、ベースの型の部分集合のイメージだから以下のようにすることは可能。

// 特定の文字列の場合
const hoge = "ほげほげ"; // リテラル型 "ほげほげ" になる
fuga(hoge);
function fuga(text: string) { // string型を許容しているが、今回のリテラル型はstring型の部分集合なので格納できる
  return `${text}です`;
}

// 特定の数値配列の場合
const foo = [1, 2, 3];
bar(foo);
function bar(array: number[]) { // number[]型を許容しているが、今回のリテラル型はnumber[]型の部分集合なので格納できる
  return array.map((item) => item * 2);
}

ジェネリクス型での利用

ジェネリクス型を使用するときに以下のように書くことがある。

type Generic<T> = T;
const hoge: Generic<string> = "hello";
const fuga: Generic<"hello"> = "hello";

この引数として渡している"hello"は値としてではなくリテラル型"hello"になっている。
ここが値だと思っていると混乱のタネになりがち。

Discussion