TypeScript の 再帰的型定義
レベル 5326 打鍵
JSONValue は再帰型で、配列やオブジェクトの中身もまた JSONValue なので、任意の正しい JSON 構造に型を付けられます。そのオブジェクトを JSON.stringify で2スペースのインデント付きで表示します。
TypeScript のコード
// 任意の JSON 値。最後の2つは JSONValue を再び参照する1type JSONValue = string | number | boolean | null | JSONArray | JSONObject;// 要素が JSON 値である配列2interface JSONArray extends Array<JSONValue> {}3interface JSONObject { // 任意の文字列キーに任意の JSON 値を入れられる4 [key: string]: JSONValue;5}// プリミティブ、配列、ネストしたオブジェクトが混在する6const data: JSONObject = {7 name: "Alice",8 age: 30,9 active: true, // 各要素がまた JSONValue なので正しい10 tags: ["dev", "ts"],11 meta: { level: 5 }12};// null は replacer なし、2 は2スペースのインデント。複数行の JSON を表示する13console.log(JSON.stringify(data, null, 2));実行結果
{
"name": "Alice",
"age": 30,
"active": true,
"tags": [
"dev",
"ts"
],
"meta": {
"level": 5
}
}このコードでタイピング練習ができます。記録はランキングに反映されません。
このコードで使う記号
この TypeScript のコードで打つ記号と、出てくる回数です。
:× 9,× 7"× 6|× 5;× 4{× 4}× 4.× 2(× 2)× 2