json-schema-to-typescript
json-schema-to-typescript copied to clipboard
Support for `"type": "date-time"`
Could you please add support for the types date-time, date, and time?
That's a great suggestion @ellis! Since these go in the format field and don't refer to types, the best we can do is generate type aliases (we can think about making them optionally opaque down the line when TypeScript adds support for nominal types). Something like:
/**
* This represents a string in RFC3339 date format.
* Eg. `2018 09 18`
*/
type DateString = string
/**
* This represents a string in RFC3339 date format.
* Eg. `24 59 58`
*/
type TimeString = string
// After
interface MyInterface {
startDate: DateString
endTime: TimeString
}
// Before
interface MyInterface {
startDate: string
endTime: string
}
Contributions are welcome.
If you'd like to take this on:
- The JSON-Schema spec talks about these 3 formats here: http://json-schema.org/latest/json-schema-validation.html#rfc.section.7.3.1
- The 3 formats are specified here: https://tools.ietf.org/html/rfc3339#section-5
For now nominal types can be expressed via
type DateString = string & {__tag: 'DateString'};
Can we implement it like this? (Also typescript inside use such solution)
most people will use use a parser/reviver that supports actual Date objects,
maybe a flexible solution would be make these configurable?:
compile(user, 'User', {
formatTypes: {
'date': 'Date',
'date-time': 'Date',
},
});
I managed to get the above using the tsType property
import {map} from 'ramda';
const prepareSchema = (schema: any) =>
typeof schema === 'object'
? schema.format === 'date' || schema.format === 'date-time'
? { ...schema, tsType: 'Date' }
: map(prepareSchema, schema)
: schema;
compile(prepareSchema(user), 'User');
Is there a support plan now?
3 years since the issue has been created. Can you please share whether this is not on a roadmap or can we expect it at some point in the future?
Thank you for your work
Guys is it available yet? I have to change format to date from date-time manually every time I run this script :(
We can use the tsType property in our JSON schema to override the type. tsType Overrides the type that's generated from the schema. Helpful in forcing a type to any or when using non-standard JSON schema extensions.
For Example, the JSON schema given below generates a type birthday with date as it's type.
const birthday = {
name: `birthday `,
type: `string`,
tsType: `Date`,
format: `date-time`,
}
export type birthday = Date;