arktype
arktype copied to clipboard
Default value morph
This would add an assignment operator (=
) that would add undefined as a valid input type (or make a key optional) and create a morph to the specified literal value.
const defaultedString = type("string='foo'")
const defaultedAtKey = type({
// have to decide whether to require ? on the key here or not
key: "number=5"
})
const tupleExpressionDefault = type([{a: "boolean" }, "=", {a: true}])
const chainedDefault = type(["number"]).default([1337])
I would propose using "nullish coalescing operator" ??
as a more understandable alternative
Or "nullish assignment operator" ??=
I would propose using "nullish coalescing operator" ?? as a more understandable alternative
Defining default values using =
is existing syntax for defaults for both functional and generic parameters.
I'd have to do a bit more thinking on this, but intuitively it seems like =
would only apply if the key was not provided at all. If it was provided, but had a value of undefined
or null
, I think the value would be undefined
or null
so that would have to be included in the original type for validation to pass.
This preserves the parallel of the existing behavior with exactOptionalPropertyTypes
. I'd have to think about what kind of behavior this would entail for shallow types like type("string='foo'")
, but that seems like a niche case.
Depending on how people would use this in practice though, I could see it being impractical to enforce the "correct" behavior here, so open to the idea we may have to compromise and default undefined
(and maybe null
).
Wow it works now, it's time to try. Is it docs ready? @ssalbdivad
@Senbonzakura1234 Working on updated docs at https://arktype.io now!
The syntax that is currently supported for defining default values on a key is:
type({ foo: "string", bar: ["number", "=", 5] })