The options
- Interfaces or types
-
Each object becomes
interface Order { … }ortype Order = { … };. They type the JSON the same way; pick the one your code base uses. An object that was always empty is written astype X = Record<string, never>either way. - Export
-
Exports every type. Without it the file still ends with
export {};, so it stays a module and its types can't merge with a global of the same name, such as the DOM'sScreen. - Read-only
- Marks every property and array
readonly. - Root type name
- The name of the outermost type, or of each item when the JSON is an array.
How values become types
Optional and nullable
A property missing from some objects becomes optional (email?: string); one that is
null in some becomes string | null. One that is only ever
null, or whose values are of different kinds, becomes unknown.
Numbers, dates and GUIDs
Numbers are number, and dates and GUIDs string, which is what
JSON.parse gives you. Where some numbers are beyond ±253, a comment warns
that JSON.parse may lose their digits.
Names
Properties keep their JSON names; names that aren't plain identifiers are quoted ("first-name": string). Type names are PascalCase, and the items of an array are named in the singular (orders
gives Order). Objects under the same key with the same properties, of the same types,
share one type.
Requirements
The code needs TypeScript 3.4 or later. It is tested by type-checking the sample JSON against it with the TypeScript 6 compiler, in strict mode.
Questions
How do I use the types?
Type what you parse: const order = JSON.parse(text) as Root;, or
await response.json() as Root. The types describe the sample; they don't check data at
run time, so validate input you don't control.
Why is a property unknown?
Its values were all null, or of different kinds, so there was nothing to tell its type
from; an array that was always empty gives unknown[] for the same reason. The notes
under the code list each such place; a sample with a real value there gives a real type.
Is my JSON uploaded?
No. It is parsed and converted in your browser, and the page's security policy blocks every network request from its scripts.