TypeScript の 型安全なAPIクライアント
レベル 5463 打鍵
型安全な API クライアントは、エンドポイント文字列を使って ResponseMap からレスポンスの型を引くので、fetchAPI("/users") はキャストなしでユーザー配列の Promise を返します。
TypeScript のコード
// 許可されるのはこの2つのエンドポイントだけ1type Endpoint = "/users" | "/posts";// 対応表: エンドポイント → レスポンスの型2type ResponseMap = {3 "/users": { id: number; name: string }[];4 "/posts": { id: number; title: string }[];5};// E は引数から推論され、対応するレスポンス型を選ぶ6async function fetchAPI<E extends Endpoint>(endpoint: E): Promise<ResponseMap[E]> { // 本物の HTTP リクエストの代わりの仮データ7 const data: ResponseMap = {8 "/users": [{ id: 1, name: "Alice" }],9 "/posts": [{ id: 1, title: "Hello" }]10 }; // E で添字アクセスすると ResponseMap[E] になり、async が Promise で包む11 return data[endpoint];12}13async function main() { // users の型は { id: number; name: string }[]14 const users = await fetchAPI("/users"); // name の存在が分かっている。「Alice」を表示する15 console.log(users[0].name);16}// 非同期関数を実行する17main();実行結果
Alice
このコードでタイピング練習ができます。記録はランキングに反映されません。
このコードで使う記号
この TypeScript のコードで打つ記号と、出てくる回数です。
"× 18:× 15;× 11{× 8}× 8[× 7]× 7/× 7(× 5)× 5