Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick multiple generic inheritance within typescript type

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:

  • Current = AdditinalAttributes<'number'>TypeableAttributes
  • Target = AdditinalAttributes<'number'>TypeableAttributes & NumericAttributes

Relevant 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  :

    { }
)
like image 802
Shalev Sror Avatar asked Feb 27 '26 09:02

Shalev Sror


1 Answers

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

like image 200
jcalz Avatar answered Mar 02 '26 14:03

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!