A
arktype3mo ago
cowboyd

Defining Records with narrowed keys

I couldn't find a way in the docs on object types (https://arktype.io/docs/objects) to define a record with narrowed keys. For example keys with no special symbols in them: BAD
{
"$userName": "bob"
}
{
"$userName": "bob"
}
GOOD
{
"userName": "bob",
}
{
"userName": "bob",
}
Seems like there should be a way, but I haven't been able to locate it.
ArkType
ArkType Docs
TypeScript's 1:1 validator, optimized from editor to runtime
7 Replies
TizzySaurus
TizzySaurus3mo ago
You can use index signatures for anything regex-compatible
type({'/[a-z]+/': 'unknown'}); // allow any key comprised entirely of lowercase letters, with any value
type({'/[a-z]+/': 'unknown'}); // allow any key comprised entirely of lowercase letters, with any value
cowboyd
cowboydOP3mo ago
nice! Is error messaging configurable on that in the case of a failure?
TizzySaurus
TizzySaurus3mo ago
Iirc you can use .configure for that E.g.
type(...).configure({message: (ctx) => `no special characters (was ${ctx.actual})`})
type(...).configure({message: (ctx) => `no special characters (was ${ctx.actual})`})
cowboyd
cowboydOP3mo ago
Ok, I can give that a shot. Cheers 🙏 Also, not really clear how I configure just the index type, and not the value type.
TizzySaurus
TizzySaurus3mo ago
If you look at the docs you can override specific error codes, I.e. figure out the error code for violating the key and overwrite its message I guess I've forgotten how to do index signatures correctly. You can scan through the docs / unit tests to figure that out
TizzySaurus
TizzySaurus3mo ago
https://arktype.io/docs/objects#properties-index Looks like it might be {"[/[a-z]+/]": "string"}
ArkType
ArkType Docs
TypeScript's 1:1 validator, optimized from editor to runtime

Did you find this page helpful?