Search code examples
typescriptd3.js

Typescript error d3 RGBColor not having r, g, b properties


I'm trying to add opacity on colors using a d3 colorscale with diverging scheme. Here's what I got so far :

const data = [-3, -2, -1, 0, 1, 2, 3];
const colorScale = d3.scaleDiverging(d3.interpolateRdBu).domain([-3, 0, 3]);
const fooColor = colorScale(2); // returns rgb(58, 132, 187)

Now if I want to add opacity to that color, I need to retrieve r,g,b values and recreate some rgba string like that :

const rgbColor = d3.color(fooColor);
const rgbaColor = "rgba(" + rgbColor?.r + "," + rgbColor?.g + "," + rgbColor?.b + "," + 0.7 + ")";

This gives some typescript error : Property 'r' does not exist on type 'RGBColor | HSLColor'.. Same for g and b properties. Yet, if I print the rgbColor object, it does have r, g, b and opacity properties.

Anyone having the same error ?

By the way, if someone knows a way to get d3 scheme working with opacity without having to make such hack, please share your solution :)


Solution

  • You're encountering this TypeScript error because the d3.color(fooColor) function can return either an RGBColor or an HSLColor, and TypeScript cannot guarantee that r, g, and b properties exist on both types. However, these properties only exist on RGBColor. To avoid the error, you can safely cast the color to RGBColor like this:

    const rgbColor = d3.color(fooColor) as d3.RGBColor;
    const rgbaColor = `rgba(${rgbColor.r}, ${rgbColor.g}, ${rgbColor.b}, 0.7)`;