Skip to content

Commit

Permalink
add rudimentary union support to JSONSchemaType
Browse files Browse the repository at this point in the history
  • Loading branch information
erikbrinkman committed Mar 13, 2021
1 parent 663ee00 commit 0c9bddc
Show file tree
Hide file tree
Showing 2 changed files with 176 additions and 74 deletions.
157 changes: 83 additions & 74 deletions lib/types/json-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,75 +7,91 @@ 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
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
}
: 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>
})
| {
anyOf: readonly JSONSchemaType<T, _partial>[]
}
: T extends null
? {
nullable: true
| {
oneOf: readonly JSONSchemaType<T, _partial>[]
}
: never) & {
) & {
[keyword: string]: any
$id?: string
$ref?: string
Expand All @@ -85,13 +101,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
93 changes: 93 additions & 0 deletions spec/types/json-schema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,43 @@ const mySchema: JSONSchemaType<MyData> & {
required: ["foo", "baz", "arr", "map"], // any other property added here won't typecheck
}

type MyUnionData = {a: number} | string

const myUnionSchema: JSONSchemaType<MyUnionData> = {
anyOf: [
{
type: "object",
properties: {
a: {type: "number"},
},
required: ["a"],
},
{
type: "string",
},
],
}

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

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

Expand Down Expand Up @@ -132,6 +169,62 @@ describe("JSONSchemaType type and validation as a type guard", () => {
})
})

const validUnionData: unknown = {
a: 5,
}

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 {
validUnionData.a.should.equal(5)
}
} 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 {
validUnionData.a.should.equal(5)
}
} 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 {
validUnionData.a.should.equal(5)
}
} 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 {
validUnionData.a.should.equal(5)
}
} 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 Down

0 comments on commit 0c9bddc

Please sign in to comment.