#"Link" two union types together

7 messages · Page 1 of 1 (latest)

pastel bolt
#

I have the following code

colorFormat.type
         // ^ "rgb" | "hsl" | "hsv"

colorFormat.value
         // ^ RGB | HSL | HSV

const hex = convert[colorFormat.type].hex(colorFormat.value);

For example convert.rgb.hex will convert rgb => hex, same for others

The above code errors because if I have:

convert.rgb.hex(  );
             // ^ type RGB must be here, but receives RGB | HSL | HSV

I need to somehow "link" these two types together, such that typescript will know that if type: "rgb" then value: RGB

I have already created a type that attempts to link them like that:

export type ColorFormatMapping = {
  rgb: RGB;
  hsl: HSL;
  hsv: HSV;
}

But I have no idea how to use it to achieve the desired effect. any ideas?

slender helmBOT
#
type ColorFormat
  = { type: 'rgb', value: 'RGB' }
  | { type: 'hsl', value: 'HSL' }
  | { type: 'hsv', value: 'HSV' }

declare const colorFormat: ColorFormat
if (colorFormat.type === 'rgb') {
    colorFormat.value
//              ^? - (property) value: "RGB"
}
iron mural
#

you probably need to use if/else or switch statement to get it to narrow

#
switch (colorFormat.type) {
    case "rgb": {
        //
        break
    }
}
#

etc

pastel bolt
iron mural
#

!:corr*