TypeScript リファレンス
実行できる例で、JSON の検証、オプション値の扱い、判別可能なユニオンを学びます。
サンプルの実行方法
TypeScript と Node.js を用意し、各例を example.ts として保存します。tsc --strict example.ts を実行し、続いて node example.js を実行します。
読み込んだ JSON を実行時に検証する
読み込んだ JSON を unknown に代入し、使用前に構造とフィールドの型を確かめます。検証に通ると型ガードによって型が絞られます。
typescript
type Config = { port: number };
function isConfig(value: unknown): value is Config {
return typeof value === "object" && value !== null &&
"port" in value && typeof value.port === "number";
}
const input: unknown = JSON.parse('{"port":8080}');
if (isConfig(input)) console.log(input.port);出力例
8080よくある間違い
as Config のような型アサーションでは入力を検証できません。JSON の構文エラーと値の不正は別々に扱います。
既定値を設定するときに false と 0 を保つ
null または undefined の場合だけ既定値を使うには、ヌル合体演算子 ?? を使います。
typescript
type Options = { retries?: number; enabled?: boolean };
const options: Options = { retries: 0, enabled: false };
console.log(options.retries ?? 3, options.enabled ?? true);出力例
0 falseよくある間違い
|| は 0、false、空文字列でも既定値に切り替わります。これらが有効な入力か確かめます。
結果の型で成功と失敗を分ける
各結果に異なるリテラルのタグを付けます。タグを調べると、その分岐にあるフィールドだけを使えます。
typescript
type Result =
| { kind: "ok"; value: number }
| { kind: "error"; message: string };
function readCount(text: string): Result {
return /^\d+$/.test(text)
? { kind: "ok", value: Number(text) }
: { kind: "error", message: "Expected digits" };
}
for (const input of ["12", "12px"]) {
const result = readCount(input);
console.log(result.kind === "ok" ? result.value : result.message);
}出力例
12
Expected digitsよくある間違い
value と error が両方オプションだと、どちらもない状態を表せます。分岐ごとに型を定義すれば、その状態を除外できます。