A
arktype3mo ago
Tom

default value for array

Is it possible to set the default value for an array to an empty array? I'm trying to do something like this:
const Thing = type({
array: "number.integer[] = []",
})
const Thing = type({
array: "number.integer[] = []",
})
But I get Default value '[]' must a literal value`
5 Replies
Tom
TomOP3mo ago
I worked it out!
array: type("number.integer[]").default(() => []),
array: type("number.integer[]").default(() => []),
Eric
Eric5w ago
Have you found a solution for optional keys? https://x.com/ericclemmons/status/1951348521392566704
Eric Clemmons, CEO of JavaScript Fatigue (@ericclemmons)
This is weird. Is there no way to do defaults with @arktypeio ? https://t.co/0nYnC1xIjN type({ 'port?': type('number').default(() => 3000), 'scopes?': type(Scope.array()).default(() => [...]) })
X
ssalbdivad
ssalbdivad4w ago
If you add a default value to a key, it will be inferred as optional automatically. Maybe it would be clearer if the type error said something more like that? But essentially it just doesn't allow optional keys there because it is redundant/potentially a source of confusing as the behavior would be equivalent with the key being defined as required.
No description
Eric
Eric4w ago
Ah. The issue I was having was passing in options where the caller shouldn’t have to specify port. Could’ve sworn that even with default provided it was a required argument and throwing a type error at the call site.
ssalbdivad
ssalbdivad4w ago
Let me know if you have a repro for that because keys with default values should always allow a missing value. One issue you might run into is if the object explicitly has undefined as the value, you'd need to use a .pipe to handle that if you want to treat it as if the value were missing.

Did you find this page helpful?