Nested morph with union of object : T | T[ ] => T[]
#1374
-
Issue: Handling morph operations on data that can be either an object or arrayProblem DescriptionI'm attempting to perform a morph operation on data that can be either an object ( Code Example// This is the object, that can have nested properties with specific morphs
const myData = type({
'bool': type('string').pipe(v => v === 'true'),
})
const toArray = <T>(data: T | T[]) => Array.isArray(data) ? data : [data]
const myType = type({
'props?': "string",
'objectArray?': type(myData, '=>', v => toArray(v)).or([type(myData.array()), "=>", v => toArray(v)])
}) ErrorWhen running this code, I receive the following error:
ContextI've searched for solutions in the documentation, issues, and Discord. I understand the error is caused by using a union type with overlapping rules as explained in the union documentation. This pattern is necessary for my use case because my XML parser returns either an object or a list depending on the number of elements. It also returns booleans as strings that need to be converted to actual boolean values. QuestionHow can I properly handle this kind of transformation while avoiding the overlapping input error? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
If you reference the same morph directly, it's safe: const myType = type({
"props?": "string",
"objectArray?": type(myData, "=>", toArray).or([
type(myData.array()),
"=>",
toArray
])
}) Referencing a morph directly (as opposed to wrapping in another anonymous arrow function) allows introspection to determine the types are equivalent. There's actually a builtin const myType = type({
"props?": "string",
"objectArray?": type.keywords.Array.liftFrom(myData)
}) Unfortunately, it runs into the same issue you mentioned. I've created an issue to track identifying that case as safe from |
Beta Was this translation helpful? Give feedback.
If you reference the same morph directly, it's safe:
Referencing a morph directly (as opposed to wrapping in another anonymous arrow function) allows introspection to determine the types are equivalent.
There's actually a builtin
Array.liftFrom
keyword for this:Unfortunately, it runs into the same issue you mentioned.
I've created an issue to track identifying that case as safe from
Array.liftFrom
:#1375