A
arktype•13mo ago
jacksteamdev

Unions with optional params?

Are unions with optional params supported in arktype? Example:
import { type, union } from "arktype"

const a = type({
direction: "'forward' | 'backward'",
"operator?": "'by'"
})

const b = type({
duration: "'s' | 'min' | 'h'",
"operator?": "'to'"
})

const c = union(a, b)

type TypeC = typeof c.infer

const test: TypeC = {
direction: "forward"
}

console.log("a", a(test))
console.log("c", c(test))

c.assert(test) // operator must be 'by' or 'to' (was undefined)
import { type, union } from "arktype"

const a = type({
direction: "'forward' | 'backward'",
"operator?": "'by'"
})

const b = type({
duration: "'s' | 'min' | 'h'",
"operator?": "'to'"
})

const c = union(a, b)

type TypeC = typeof c.infer

const test: TypeC = {
direction: "forward"
}

console.log("a", a(test))
console.log("c", c(test))

c.assert(test) // operator must be 'by' or 'to' (was undefined)
https://stackblitz.com/edit/fhz11y?file=type.ts
Jack Steam
StackBlitz
D4tqcy (forked) - StackBlitz
ArkType type demo
1 Reply
ssalbdivad
ssalbdivad•13mo ago
I think in the StackBlitz // operator should be commented out on line 19 to repro the bug? But yeah, this is definitely a bug. Probably to do with discrimination if I had to guess- maybe there is some issue with discriminating on an optional key? Yeah, it does look like that. You can see the structure of what it's checking here:
[
["domain", "object"],
[
"switch",
{
path: ["operator"],
kind: "value",
cases: {
"'by'": [
[
"requiredProp",
[
"direction",
[
["domain", "string"],
[
"switch",
{
path: [],
kind: "value",
cases: {
"'forward'": [],
"'backward'": []
}
}
]
]
]
]
],
"'to'": [
[
"requiredProp",
[
"duration",
[
["domain", "string"],
[
"switch",
{
path: [],
kind: "value",
cases: {
"'s'": [],
"'min'": [],
"'h'": []
}
}
]
]
]
]
]
}
}
]
]
[
["domain", "object"],
[
"switch",
{
path: ["operator"],
kind: "value",
cases: {
"'by'": [
[
"requiredProp",
[
"direction",
[
["domain", "string"],
[
"switch",
{
path: [],
kind: "value",
cases: {
"'forward'": [],
"'backward'": []
}
}
]
]
]
]
],
"'to'": [
[
"requiredProp",
[
"duration",
[
["domain", "string"],
[
"switch",
{
path: [],
kind: "value",
cases: {
"'s'": [],
"'min'": [],
"'h'": []
}
}
]
]
]
]
]
}
}
]
]
It incorrectly discriminates on 'operatator' even though it's not required in all branches This seems like something I could likely fix trivially, let me check @jacksteamdev Well, wasn't quite as trivial as I was hoping- the new TypeNodes are so much easier to work with than the old ones 😅 Anyways, try 1.0.26-alpha
Want results from more Discord servers?
Add your server