Skip to content

Commit

Permalink
Merge pull request ajv-validator#1485 from erikbrinkman/unions
Browse files Browse the repository at this point in the history
add union support to JSONSchemaType
  • Loading branch information
epoberezkin authored Mar 15, 2021
2 parents e592bf2 + e98762a commit 9944015
Show file tree
Hide file tree
Showing 3 changed files with 255 additions and 75 deletions.
33 changes: 33 additions & 0 deletions docs/guide/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,36 @@ function parseAndLogFoo(json: string): void {
```
</code-block>
</code-group>

## Type-safe Unions

JSON Type Definition only supports tagged unions, so unions in JTD are fully supported for `JTDSchemaType` and `JTDDataType`.
JSON Schema is more complex and so `JSONSchemaType` has limited support for type safe unions.
`JSONSchemaType` will type check unions where each union element is fully specified as an element of an `anyOf` array or `oneOf` array.
Additionaly, unions of primitives will type check appropriately if they're combined into an array `type`, e.g. `{ type: ["string", "number"] }`.
Note that due to current restrictions in typescript, these can't verify that every element is typechecked, and the following example is still valid `const schema: JSONSchemaType<number | string> = { type: "string" }`.

Here's a more detailed example showing several union types:
<code-group>
<code-block title="JSON Schema">
```typescript
import Ajv, {JSONSchemaType} from "ajv"
const ajv = new Ajv()

type MyUnion = { prop: boolean } | string | number

const schema: JSONSchemaType<MyUnion> = {
anyOf: [
{
type: "object",
properties: { prop: { type: "boolean" } },
required: ["prop"],
},
{
type: ["string", "number"]
}
]
}
```
</code-block>
</code-group>
180 changes: 106 additions & 74 deletions lib/types/json-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,75 +7,114 @@ type JSONType<T extends string, _partial extends boolean> = _partial extends tru
? T | undefined
: T

export type JSONSchemaType<T, _partial extends boolean = false> = (T extends number
? {
type: JSONType<"number" | "integer", _partial>
minimum?: number
maximum?: number
exclusiveMinimum?: number
exclusiveMaximum?: number
multipleOf?: number
format?: string
}
: T extends string
? {
type: JSONType<"string", _partial>
minLength?: number
maxLength?: number
pattern?: string
format?: string
}
: T extends boolean
? {
type: "boolean"
}
: T extends [any, ...any[]]
? {
// JSON AnySchema for tuple
type: JSONType<"array", _partial>
items: {
readonly [K in keyof T]-?: JSONSchemaType<T[K]> & Nullable<T[K]>
} & {length: T["length"]}
minItems: T["length"]
} & ({maxItems: T["length"]} | {additionalItems: false})
: T extends readonly any[]
? {
type: JSONType<"array", _partial>
items: JSONSchemaType<T[0]>
contains?: PartialSchema<T[0]>
minItems?: number
maxItems?: number
minContains?: number
maxContains?: number
uniqueItems?: true
additionalItems?: never
}
: T extends Record<string, any>
? {
// JSON AnySchema for records and dictionaries
// "required" is not optional because it is often forgotten
// "properties" are optional for more concise dictionary schemas
// "patternProperties" and can be only used with interfaces that have string index
type: JSONType<"object", _partial>
// "required" type does not guarantee that all required properties are listed
// it only asserts that optional cannot be listed
required: _partial extends true ? Readonly<(keyof T)[]> : Readonly<RequiredMembers<T>[]>
additionalProperties?: boolean | JSONSchemaType<T[string]>
unevaluatedProperties?: boolean | JSONSchemaType<T[string]>
properties?: _partial extends true ? Partial<PropertiesSchema<T>> : PropertiesSchema<T>
patternProperties?: {[Pattern in string]?: JSONSchemaType<T[string]>}
propertyNames?: JSONSchemaType<string>
dependencies?: {[K in keyof T]?: Readonly<(keyof T)[]> | PartialSchema<T>}
dependentRequired?: {[K in keyof T]?: Readonly<(keyof T)[]>}
dependentSchemas?: {[K in keyof T]?: PartialSchema<T>}
minProperties?: number
maxProperties?: number
interface NumberKeywords {
minimum?: number
maximum?: number
exclusiveMinimum?: number
exclusiveMaximum?: number
multipleOf?: number
format?: string
}

interface StringKeywords {
minLength?: number
maxLength?: number
pattern?: string
format?: string
}

export type JSONSchemaType<T, _partial extends boolean = false> = (
| ((T extends number
? {
type: JSONType<"number" | "integer", _partial>
} & NumberKeywords
: T extends string
? {
type: JSONType<"string", _partial>
} & StringKeywords
: T extends boolean
? {
type: "boolean"
}
: T extends [any, ...any[]]
? {
// JSON AnySchema for tuple
type: JSONType<"array", _partial>
items: {
readonly [K in keyof T]-?: JSONSchemaType<T[K]> & Nullable<T[K]>
} & {length: T["length"]}
minItems: T["length"]
} & ({maxItems: T["length"]} | {additionalItems: false})
: T extends readonly any[]
? {
type: JSONType<"array", _partial>
items: JSONSchemaType<T[0]>
contains?: PartialSchema<T[0]>
minItems?: number
maxItems?: number
minContains?: number
maxContains?: number
uniqueItems?: true
additionalItems?: never
}
: T extends Record<string, any>
? {
// JSON AnySchema for records and dictionaries
// "required" is not optional because it is often forgotten
// "properties" are optional for more concise dictionary schemas
// "patternProperties" and can be only used with interfaces that have string index
type: JSONType<"object", _partial>
// "required" type does not guarantee that all required properties are listed
// it only asserts that optional cannot be listed
required: _partial extends true ? Readonly<(keyof T)[]> : Readonly<RequiredMembers<T>[]>
additionalProperties?: boolean | JSONSchemaType<T[string]>
unevaluatedProperties?: boolean | JSONSchemaType<T[string]>
properties?: _partial extends true ? Partial<PropertiesSchema<T>> : PropertiesSchema<T>
patternProperties?: {[Pattern in string]?: JSONSchemaType<T[string]>}
propertyNames?: JSONSchemaType<string>
dependencies?: {[K in keyof T]?: Readonly<(keyof T)[]> | PartialSchema<T>}
dependentRequired?: {[K in keyof T]?: Readonly<(keyof T)[]>}
dependentSchemas?: {[K in keyof T]?: PartialSchema<T>}
minProperties?: number
maxProperties?: number
}
: T extends null
? {
nullable: true
}
: never) & {
allOf?: Readonly<PartialSchema<T>[]>
anyOf?: Readonly<PartialSchema<T>[]>
oneOf?: Readonly<PartialSchema<T>[]>
if?: PartialSchema<T>
then?: PartialSchema<T>
else?: PartialSchema<T>
not?: PartialSchema<T>
})
// these two unions allow arbitrary unions of types
| {
anyOf: readonly JSONSchemaType<T, _partial>[]
}
: T extends null
? {
nullable: true
| {
oneOf: readonly JSONSchemaType<T, _partial>[]
}
: never) & {
// 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
$ref?: string
Expand All @@ -85,13 +124,6 @@ export type JSONSchemaType<T, _partial extends boolean = false> = (T extends num
definitions?: {
[Key in string]?: JSONSchemaType<Known, true>
}
allOf?: Readonly<PartialSchema<T>[]>
anyOf?: Readonly<PartialSchema<T>[]>
oneOf?: Readonly<PartialSchema<T>[]>
if?: PartialSchema<T>
then?: PartialSchema<T>
else?: PartialSchema<T>
not?: PartialSchema<T>
}

type Known = KnownRecord | [Known, ...Known[]] | Known[] | number | string | boolean | null
Expand Down
117 changes: 116 additions & 1 deletion spec/types/json-schema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,56 @@ const mySchema: JSONSchemaType<MyData> & {
required: ["foo", "baz", "arr", "map"], // any other property added here won't typecheck
}

type MyUnionData = {a: boolean} | string | number

const myUnionSchema: JSONSchemaType<MyUnionData> = {
anyOf: [
{
type: "object",
properties: {
a: {type: "boolean"},
},
required: ["a"],
},
{
type: ["string", "number"],
// can specify properties for either type
minimum: 0,
minLength: 1,
},
],
}

// because of the current definition, you can do this nested recusion
const myNestedUnionSchema: JSONSchemaType<MyUnionData> = {
anyOf: [
{
oneOf: [
{
type: "object",
properties: {
a: {type: "boolean"},
},
required: ["a"],
},
{
type: "string",
},
],
},
{
type: "number",
},
],
}

// @ts-expect-error can't use empty array for invalid type
const invalidSchema: JSONSchemaType<MyData> = {
type: [],
}

describe("JSONSchemaType type and validation as a type guard", () => {
const ajv = new _Ajv()
const ajv = new _Ajv({allowUnionTypes: true})

const validData: unknown = {
foo: "foo",
Expand Down Expand Up @@ -132,6 +180,70 @@ describe("JSONSchemaType type and validation as a type guard", () => {
})
})

const validUnionData: unknown = {
a: true,
}

describe("schema has type JSONSchemaType<MyUnionData>", () => {
it("should prove the type of validated data", () => {
const validate = ajv.compile(myUnionSchema)
if (validate(validUnionData)) {
if (typeof validUnionData === "string") {
should.fail("not a string")
} else if (typeof validUnionData === "number") {
should.fail("not a number")
} else {
validUnionData.a.should.equal(true)
}
} else {
should.fail("is valid")
}
should.not.exist(validate.errors)

if (ajv.validate(myUnionSchema, validUnionData)) {
if (typeof validUnionData === "string") {
should.fail("not a string")
} else if (typeof validUnionData === "number") {
should.fail("not a number")
} else {
validUnionData.a.should.equal(true)
}
} else {
should.fail("is valid")
}
should.not.exist(ajv.errors)
})

it("should prove the type of validated nested data", () => {
const validate = ajv.compile(myNestedUnionSchema)
if (validate(validUnionData)) {
if (typeof validUnionData === "string") {
should.fail("not a string")
} else if (typeof validUnionData === "number") {
should.fail("not a number")
} else {
validUnionData.a.should.equal(true)
}
} else {
should.fail("is valid")
}
should.not.exist(validate.errors)

if (ajv.validate(myNestedUnionSchema, validUnionData)) {
if (typeof validUnionData === "string") {
should.fail("not a string")
} else if (typeof validUnionData === "number") {
should.fail("not a number")
} else {
validUnionData.a.should.equal(true)
}
} else {
should.fail("is valid")
}
should.not.exist(ajv.errors)
})
})

describe("schema has type SchemaObject", () => {
it("should prove the type of validated data", () => {
const schema = mySchema as SchemaObject
Expand All @@ -148,3 +260,6 @@ describe("JSONSchemaType type and validation as a type guard", () => {
})
})
})

// eslint-disable-next-line no-void
void invalidSchema

0 comments on commit 9944015

Please sign in to comment.