JSON 轉 TypeScript
從 JSON 範例產生 TypeScript 介面。
使用範例
快速搭建 API 回應的型別骨架
貼上伺服器傳回的 JSON 回應範例,即可取得可直接貼進專案的 TypeScript 介面草稿。
自動把巢狀物件拆成獨立介面
當 JSON 中包含另一個物件時,會依欄位名稱產生專屬的具名介面,讓結構保持整潔。
陣列項目欄位不同時標示為選填
當陣列中的物件並非每個都有相同欄位時,會合併成一個介面,並在非所有項目都有的欄位加上「?」選填標記。
為 GraphQL 或 webhook 內容快速建立型別原型
貼上像 '{"event": "order.created", "data": {"id": "ord_1", "total": 42.5}}' 這樣的範例內容,快速取得 webhook 處理常式所需的型別介面,不必手動撰寫。
檢查 null 值如何定義型別
在範例中加入像 '{"middleName": null}' 這樣的欄位,看看工具如何在產生的介面中表示可為 null 的欄位。
快速參考
JSON values → TypeScript types
| JSON | TypeScript |
|---|---|
| "hello" | type Root = string; |
| 42 | type Root = number; |
| 3.14 | type Root = number; |
| true | type Root = boolean; |
| null | type Root = null; |
| [] | type Root = unknown[]; |
| [1, 2, 3] | type Root = number[]; |
| ["a", "b"] | type Root = string[]; |
| [1, "a", true] | type Root = (number | string | boolean)[]; |
| [1, null] | type Root = (number | null)[]; |
| [[1, 2], [3]] | type Root = number[][]; |
| {} | interface Root { } |
JSON objects → TypeScript interfaces
| JSON | TypeScript |
|---|---|
| {"id": 1, "name": "Ada"} | interface Root { id: number; name: string; } |
| {"deletedAt": null} | interface Root { deletedAt: null; } |
| {"tags": ["a", "b"]} | interface Root { tags: string[]; } |
| {"user": {"id": 1}} | interface User { id: number; } interface Root { user: User; } |
| {"items": [{"id": 1}, {"id": 2, "note": "x"}]} | interface Item { id: number; note?: string; } interface Root { items: Item[]; } |
| {"categories": [{"name": "x"}]} | interface Category { name: string; } interface Root { categories: Category[]; } |
| {"first-name": "Ada"} | interface Root { "first-name": string; } |
| {"a": {"x": 1}, "b": {"x": 2}} | interface A { x: number; } interface Root { a: A; b: A; } |
常見問題
我輸入的 JSON 會傳送到伺服器嗎?
不會。所有轉換都只在您的瀏覽器中進行,輸入的內容不會傳送到任何伺服器。
產生的程式碼可以直接使用嗎?
這是僅憑一份 JSON 範例推論出來的結果,可能無法完全涵蓋實際資料的所有情況。建議把產生的介面當作起點,再依需要自行調整。
日期字串會被識別成 Date 型別嗎?
不會。JSON 沒有專屬的日期型別,所有字串都會視為 string。若想當作日期處理,請自行修改產生的程式碼。
如果同一種物件形狀出現多次會怎樣?
結構相同的物件會重複使用同一個介面,而不會產生重複的介面。
空陣列會如何定義型別?
由於空陣列無從得知元素的型別,它會被定義為 'unknown[]'。如果想要更具體的元素型別,請在陣列中至少加入一個範例元素。
null 值會得到什麼 TypeScript 型別?
範例值為 null 的欄位會被定義為 'null'。如果您知道該欄位也可能容納其他型別(例如字串或不存在),就需要手動放寬產生的型別,例如改為 'string | null'。
JSON 中的欄位順序會影響產生的介面嗎?
不會。欄位在產生的介面中,會依它們在您輸入中出現的相同順序列出,但在來源 JSON 中重新排序,不會對產生的型別本身造成影響。