optional() does not create an optional property on an object
See original GitHub issueoptional
does not create an optional property on an object. It should create an optional property in order to match with TypeScript validation semantics.
const CustomText = object({
name: string()
age: optional(number())
})
// creates a type like:
type UserType = {
name: string
age: number | undefined
}
// But it should create a type like this:
type UserType = {
name: string
age?: number | undefined
}
Alignment with TypeScript
The Superstruct type does not align with the TypeScript type it is returning.
As an example, this passes Superstruct validation:
describe("content-types", () => {
it("should validate content-types", async () => {
const User = object({
name: string(),
age: optional(number()),
})
assert({ name: "john" }, User)
})
})
but fails the type number | undefined
returned by Superstruct:
The red squiggles indicate the following error when hovered:
Use case
My use case is that I want to validate slate data types.
They are defined such that the bold
property is optional. To be specific, they are optional(literal(true)
. In order to make sure my validations line up against my type definitions exactly, I use unit testing to make sure the two type are equal. Because the optional types show up as a union of the passed in type and undefined but do not add the ?
to the property, they do not match and fail tests.
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (3 by maintainers)
Top GitHub Comments
@JakeElder @ianstormtaylor
This now has a PR: https://github.com/ianstormtaylor/superstruct/pull/390
Ah interesting, that seems like a decent trade off I think. Seems pretty rare that you’d explicitly want a defined
undefined
value to me.