I constructed a Typescript type named AdditinalAttributes which accepts a generic.
The type will return the first condition that matches.
I would want that the type will return the sum of the matching conditions.
Example:
AdditinalAttributes<'number'> → TypeableAttributesAdditinalAttributes<'number'> → TypeableAttributes & NumericAttributesRelevant Code:
type TypeableInputs = 'number' | 'text'
type DropdownInputs = ''
type NumericInputs = 'number'
type AdditinalAttributes<T> = (
T extends TypeableInputs ?
TypeableAttributes :
T extends DropdownInputs ?
DropdownAttributes :
T extends NumericInputs ?
NumericAttributes :
{ }
)
Since you want the output to be the intersection of the relevant types, and because the input types are keylike, you can build a helper type whose properties are automatically what you want:
type InputToAttributeMap =
Record<TypeableInputs, TypeableAttributes> &
Record<DropdownInputs, DropdownAttributes> &
Record<NumericInputs, NumericAttributes>
This uses the Record<K, V> utility type, which means "an object type with keys of type K and values of type V". By intersecting these together we can avoid conditional types. The InputToAttributeMap type is equivalent to:
type InputToAttributeMap = {
number: TypeableAttributes & NumericAttributes;
text: TypeableAttributes;
"": DropdownAttributes;
}
Then your AdditionalAttributes type just needs to index into this mapping type:
type AdditionalAttributes<K extends keyof InputToAttributeMap> =
InputToAttributeMap[K]
Let's test it:
type Target = AdditionalAttributes<"number">
//type Target = TypeableAttributes & NumericAttributes
Looks good!
Playground link to code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With