Description
Search Terms
import json
literal type
specific type
Suggestion
When importing a JSON file, strings and numbers are typed as string
and number
rather than the string or number literals in the file.
Also, array literals are imported as T[]
instead of [T1, T2, T3]
tuples.
Since the JSON is almost an object literal, I believe it makes more sense to type it more specifically.
I have faced most of my issues with the former, but I believe as much information as possible should be provided, which means tuples instead of arrays.
At least the former shouldn't be particularly breaking as the types are replaced by subtypes, but of course can be breaking if typeof
reflection is used to jam less specific types into it.
Use Cases
In a number of cases, JSON imported are expected to conform to a schema that includes specific enums. Please see example.
Examples
import * as eventSchema from './src/event.schema.json'
import { compile } from 'json-schema-to-typescript'
const typings = compile(eventSchema, 'Event')
Currently, this will not compile, because
Type
string
is not assignable to type"string" | "number" | "boolean" | "object" | "integer" | "array" | "null" | "any" | JSONSchema4TypeName[] | undefined
This forces skipping the type checking of this completely statically available, and valid, object:
const typings = compile(eventSchema as any, 'Event')
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript / JavaScript code 🤔
- This wouldn't chan 643C ge the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. new expression-level syntax)