`$ref` in `allOf` with depth of 2 is not correctly converted when multi-referenced
Closed this issue · 5 comments
I'm trying to reproduce an inheritance schema like this:
Thing
|
Vehicle
| \
Car Truck
Using the "allOf" keyword with a schema like this:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "test",
"definitions": {
"Thing": {
"type": "object",
"properties": {
"name": { "type": "string" }
},
"required": ["name"]
},
"Vehicle": {
"type": "object",
"allOf": [{ "$ref": "#/definitions/Thing" }],
"properties": {
"year": { "type": "integer" }
},
"required": ["year"]
},
"Car": {
"type": "object",
"allOf": [{ "$ref": "#/definitions/Vehicle" }],
"properties": {
"numDoors": { "type": "integer" }
},
"required": ["numDoors"]
},
"Truck": {
"type": "object",
"allOf": [{ "$ref": "#/definitions/Vehicle" }],
"properties": {
"numAxles": { "type": "integer" }
},
"required": ["numAxles"]
}
},
"oneOf": [{ "$ref": "#/definitions/Car" }, { "$ref": "#/definitions/Truck" }]
}
The output looks like this:
export type Test = Car | Truck;
export type Car = Car1 & {
numDoors: number;
};
export type Car1 = Vehicle; // <--- This is expected
export type Vehicle = Vehicle1 & {
year: number;
};
export type Vehicle1 = Thing;
export type Truck = Truck1 & {
numAxles: number;
};
export type Truck1 = Vehicle1; // <--- This is unexpected, should be Vehicle
name: string;
}
Here, Truck
is directly inheriting Thing
instead of Vehicle
, so its TypeScript definition does not includes the year
property.
If I exchange the properties of the root oneOf
, then the the issue appears in the type definition of Car
.
Thank you for your answer @bcherny !
extends
will indeed generate the correct typescript classes, but then the validation will be incorrect, because the properties of the "parent" objets won't be required anymore and {"numDoors": 2}
will become a valid input: https://jsonschema.dev/s/TdKME
@arnauddrain extends
is an old keyword that has been removed in modern JSON Schema versions. The website you linked doesn't seem to implement it correctly. If your validator supports it, extends
will work fine the way I suggested.
See the spec: https://github.com/json-schema/json-schema/wiki/Extends/014e3cd8692250baad70c361dd81f6119ad0f696
Fix included in v15.0.0.