Need help with creating a type-safe function that can accept an argument representing a prop that either has a primitive value or a specific object with values of the same primitive type. Examples include t=number
, t={x:number}
, or t={x:number,y:number}
.
For instance, consider a prop called grid which is initially of type number
but can be further specified with fields like horizontal|vertical
. Valid inputs should include grid=10
, grid={horizontal:10}
, grid={vertical:10}
, or grid={horizontal:10,vertical:10}
.
Here's a working implementation:
(implementation code here)
Now I want to make the function more generic by allowing the specification of the horizontal and vertical fields as generics as well:
(updated implementation code here)
Updated TypeScript playground link
In simpler terms, why does the following return an array instead of an object?
// previous implementation that works fine
{
horizontal: Prop extends Primitive ? Prop : Prop extends { horizontal: infer V } ? V : Default;
vertical: Prop extends Primitive ? Prop : Prop extends { vertical: infer V } ? V : Default;
}
// updated implementation that returns an array - WHY?
{
[key in keyof Spec]: Prop extends Primitive ? Prop : Prop extends { [key in keyof Spec]: infer V } ? V : Default;
}
To see complete examples and test the functionality, visit the provided TypeScript playground links. The JavaScript functions correctly but the inferred type seems to be incorrect. Any assistance would be greatly appreciated.