Closed
Description
π Search Terms
recursive conditional type compilation variable parameter
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about recursive conditional types
β― Playground Link
π» Code
type StringConstraints = { required?: boolean }
type ObjectConstraints = { required?: boolean }
type StringSchema = ["string", StringConstraints]
type ObjectSchema<T extends object | null | undefined> = ["object", { [P in keyof T]: SchemaFor<T[P]> }]
type SchemaFor<T> =
[T] extends [string | null | undefined] ? StringSchema :
[T] extends [object | null | undefined] ? ObjectSchema<T> :
never
type AnySchema = StringSchema | ObjectSchema<{}>
type Person = {
name: string | null
}
function validate(schema: AnySchema) {
return []
}
const schema1 = ["object", {
name: ["string", { required: true }],
}]
const schema2: AnySchema = ["object", {
name: ["string", { required: true }],
}]
const schema3: SchemaFor<Person> = ["object", {
name: ["string", { required: true }],
}]
validate(schema1)
// Error: Argument of type '(string | { name: (string | { required: boolean; })[]; })[]' is not assignable to parameter of type 'AnySchema'.
// Type '(string | { name: (string | { required: boolean; })[]; })[]' is not assignable to type 'ObjectSchema<{}>'.
// Target requires 2 element(s) but source may have fewer.(2345)
validate(schema2) // No type checking, name and required can be mispelled
validate(schema3) // Works as expected, type checking is ok
validate(["object", { // Works partially, type checking works on "object" but not on "string" or "required"
name: ["string", { required: true }],
}])
π Actual behavior
Type-checking only works with schema3, where all properties have to be correctly spelled. schema1 gives a compiler error (see code). schema2 can be completely misspelled with no errors. Passing directly a schema as parameter to the validate
function works partially.
π Expected behavior
All four schema definitions should work with correct and complete type-checking.
Additional information about the issue
No response