Skip to content

Commit

Permalink
improve JSONSchemaType errors
Browse files Browse the repository at this point in the history
typescript seems to report errors with the last member of a valid union
first, so this rearranges the type so the simple union types come first,
and the type that represents the meaty types comes last. This should
help make errors like the one in ajv-validator#1521 more clear.
  • Loading branch information
erikbrinkman authored and andriyl committed Jun 16, 2021
1 parent fc1a55b commit 372961d
Showing 1 changed file with 24 additions and 23 deletions.
47 changes: 24 additions & 23 deletions lib/types/json-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,30 @@ interface StringKeywords {
}

export type JSONSchemaType<T, _partial extends boolean = false> = (
| // these two unions allow arbitrary unions of types
{
anyOf: readonly JSONSchemaType<T, _partial>[]
}
| {
oneOf: readonly JSONSchemaType<T, _partial>[]
}
// this union allows for { type: (primitive)[] } style schemas
| ({
type: (T extends number
? JSONType<"number" | "integer", _partial>
: T extends string
? JSONType<"string", _partial>
: T extends boolean
? JSONType<"boolean", _partial>
: never)[]
} & (T extends number
? NumberKeywords
: T extends string
? StringKeywords
: T extends boolean
? unknown
: never))
// this covers "normal" types; it's last so typescript looks to it first for errors
| ((T extends number
? {
type: JSONType<"number" | "integer", _partial>
Expand Down Expand Up @@ -91,29 +115,6 @@ export type JSONSchemaType<T, _partial extends boolean = false> = (
else?: PartialSchema<T>
not?: PartialSchema<T>
})
// these two unions allow arbitrary unions of types
| {
anyOf: readonly JSONSchemaType<T, _partial>[]
}
| {
oneOf: readonly JSONSchemaType<T, _partial>[]
}
// this union allows for { type: (primitive)[] } style schemas
| ({
type: (T extends number
? JSONType<"number" | "integer", _partial>
: T extends string
? JSONType<"string", _partial>
: T extends boolean
? JSONType<"boolean", _partial>
: never)[]
} & (T extends number
? NumberKeywords
: T extends string
? StringKeywords
: T extends boolean
? unknown
: never))
) & {
[keyword: string]: any
$id?: string
Expand Down

0 comments on commit 372961d

Please sign in to comment.