arktype icon indicating copy to clipboard operation
arktype copied to clipboard

Default value morph

Open ssalbdivad opened this issue 1 year ago • 3 comments

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])

ssalbdivad avatar May 17 '23 02:05 ssalbdivad

I would propose using "nullish coalescing operator" ?? as a more understandable alternative

Dimava avatar May 22 '23 16:05 Dimava

Or "nullish assignment operator" ??=

Dimava avatar May 22 '23 16:05 Dimava

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).

ssalbdivad avatar May 22 '23 16:05 ssalbdivad

Wow it works now, it's time to try. Is it docs ready? @ssalbdivad

Senbonzakura1234 avatar May 17 '24 10:05 Senbonzakura1234

@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] })

ssalbdivad avatar May 17 '24 10:05 ssalbdivad