TypeScript 4.2 の Template Literal Expressions Have Template Literal Types の例
TypeScript 4.2 の Template Literal Expressions Have Template Literal Types
について。これは `/topics/${id}`
が TypeScript 4.1 までは string
型だったのが TypeScript 4.2 から `/topics/${string}`
型になったという話です。id
が number
であれば `/topics/${number}`
型にもなります。
実例。よくある API アクセスで、パスから戻り値の型を自動判定します。
export interface Topic {} async function fetchJson(path: `/topics`): Promise<Topic[]>; // ${string} は ${number} でも構いません async function fetchJson(path: `/topics/${string}`): Promise<Topic>; async function fetchJson<T>(path: string): Promise<T>; async function fetchJson<T>(path: string): Promise<T> { return (await fetch(path)).json() as Promise<T>; } // これは 4.1 でも 4.2 でも Topic[] 型 const topics = await fetchJson('/topics'); // これは 4.1 でも 4.2 でも Topic 型 const topic300 = await fetchJson('/topics/300'); // TypeScript 4.1 だと unknown 型なのが // TypeScript 4.2 だと Topic 型になる const n: number = 10 const topicN = await fetchJson(`/topics/${n}`);
表にするとこうなります。
4.1 | 4.2 | |
---|---|---|
'/topics/300' |
`/topics/${string}` 型 |
`/topics/${string}` 型 |
`/topics/${n}` |
unknown 型 |
`/topics/${string}` 型 |
便利そう〜