Union Fallthrough?
I'm transforming some input using morphs like so:
And creating a union type like this, where
otherUnit.unit
is "string":
I expected otherUnit
to catch non-matching values, but I'm getting this error:
Which makes sense if the union is unordered.
Is there a way to make this union ordered? If not, is there a more fluent way to do this than wrapping it in a function?5 Replies
Are you aware of
type("...", arrOfTypes)
? That may be what you're looking for with toStringUnion
It's not entirely clear to me what you're trying to achieve thoughHi @TizzySaurus !
My goal is to normalize recipe ingredient measurements before writing to the db. Later I have an SQL function that combines ingredients from different recipes into a grocery list.
This is
toStringUnion
:
It's not exactly a minimal repro, sorry 😓
Right now I'm wrapping it in a function:
Which works, but I was curious if there was a better way to do it.toStringUnion
should just be type("...", aliasList)
. I wouldn't even wrap it in a function since then you loose the type inference -- just use it directly
There's also type.enumerated([1, 2, 3])
iirc
What is normalizedUnitUnion
and namedUnit
?
Your type also seems to be wrong because weightAliases
is Record<string, StandardWeightUnit>
, but then you do Object.keys(weightAliases) as StandardWeightUnit[]
.
But the keys are string
, not StandardWeightUnit
. It's the values that are StandardWeightUnit
But in theory you could do something like....
Fwiw there's alsoiirc@TizzySaurus Thanks for the help!
I wasn't able to get
type("keyof", weightAliases)
working, it requires weightAliases to be a Type, as is it can't resolve the property values.
I was able to reduce casting with type.enumerated(...weightNames)
and an Object.keys wrapper:
I think what I was looking for was essentially if ... else
support for string matching:
Maybe subset matching... but I got there in the end.There's a
match
API I'll release soon for a case like this. As is, you'd just want to write it as string
and then do the narrowing logic in the pipe
function itself.
You can probably imagine why unless someone explicitly opts into ordering here, having a union where multiple branches overlap and have different piping logic is probably not desirable- but match
will be perfect for that!