Allow non-empty array literal defaults in string syntax
Request a feature
Motivation
Now that = [] and = {} work in a string definition (and each missing value gets a fresh array or object):
type({
values: "string[] = []",
meta: "object = {}"
})I noticed that a non-empty list cannot be written the same way. Both quote styles fail on 2.2.5, before the default is read. [ is not an expression opener, and the parser only special-cases the exact tokens [] and {}:
type({ HOSTS: "string[] = ['localhost']" })
// Expected an expression before '['localhost']'
type({ HOSTS: 'string[] = ["localhost"]' })
// Expected an expression before '["localhost"]'String unit defaults accept either quote (string = 'localhost' and string = "localhost"). A bare array in the tuple form is also rejected (Non-primitive default must be specified as a function), so a static list cannot be written inline at all.
#1169 shipped the empty case. Discussion #1201 mentions non-empty arrays in passing and then sets them aside. No issue tracks that case.
Solution
Accept a unit-literal array after = in string syntax, with either quote style:
const Hosts = type({
HOSTS: "string[] = ['localhost']"
// HOSTS: 'string[] = ["localhost"]'
})
Hosts.assert({}).HOSTS // ["localhost"]Each traversal should get its own array, the way = [] already does, so a push on one result does not show up on the next. The same form should work for other unit literals, such as number[] = [3000, 8080].
The existing alternatives stay for computed defaults:
type("string[]").default(() => ["localhost"])
type({ HOSTS: ["string[]", "=", () => ["localhost"]] })Embedding object or tuple types in a string, such as "{foo: string}[]", is a separate request (#1424).
Source: arktypeio/arktype