json-schema-to-ts
json-schema-to-ts copied to clipboard
...unknown[] for objects of array
trafficstars
Hello! Firstly, thanks for the library!
I have a question regarding the usage with a schema that includes an array of objects. According to the schema provided below, the following TypeScript type is generated:
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
const schema = {
$schema: 'http://json-schema.org/draft-06/schema#',
type: 'object',
additionalProperties: false,
properties: {
payments: {
type: 'array',
minItems: 1,
maxItems: 10,
items: [
{
type: 'object',
additionalProperties: false,
properties: {
type: {
$ref: '#/definitions/type_format',
},
sum: {
$ref: '#/definitions/number_two_format',
},
},
required: ['type', 'sum'],
},
],
},
},
definitions: {
number_two_format: {
type: 'number',
minimum: 0,
maximum: 100000000,
multipleOf: 0.01,
},
type_format: {
type: 'number',
enum: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
},
},
} as const satisfies JSONSchema;
export type Pay = FromSchema<typeof schema>;
// 👆
type ResultShemaType = {
payments?: [{
type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
sum: number;
}] | [{
type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
sum: number;
}, ...unknown[]] | undefined;
}
Should ResultType also include ...unknown[]?
Perhaps it would be sufficient if the final type:
type FinalType = {
payments?: {
type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
sum: number;
}[]
}
typescript: 5.4.2 json-schema-to-ts: 3.0.1
I've explored JSON Schema format a bit, and it seems like additionalItems: false fixes my issue.
upd. Now, I can use payments only as tuple with one object 🤔.
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
const schema = {
$schema: 'http://json-schema.org/draft-06/schema#',
type: 'object',
additionalProperties: false,
properties: {
payments: {
type: 'array',
minItems: 1,
maxItems: 10,
additionalItems: false, // < ---- this
items: [
{
type: 'object',
additionalProperties: false,
properties: {
type: {
$ref: '#/definitions/type_format',
},
sum: {
$ref: '#/definitions/number_two_format',
},
},
required: ['type', 'sum'],
},
],
},
},
definitions: {
number_two_format: {
type: 'number',
minimum: 0,
maximum: 100000000,
multipleOf: 0.01,
},
type_format: {
type: 'number',
enum: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
},
},
} as const satisfies JSONSchema;
export type Pay = FromSchema<typeof schema>;
// 👆
type ResultShemaType = {
payments?: [{
type: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
sum: number;
}] | undefined;
}