Home > OS >  How to use spread operator in typescript as argument to a function?
How to use spread operator in typescript as argument to a function?

Time:01-15

I want to be able to spread the array in to the argment of the function, but I am getting A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)

  const currentColor: string = context.brandingPersonal.customColor; // rgba string 
  const numberColor: [number, number, number, number] = currentColor
    .substring(5, currentColor.length - 1)
    .replace(/ /g, '')
    .split(',')
    .map((item) => Number(item));

  function getContrastColor(R: number, G: number, B: number, A?: number) {
    const brightness = R * 0.299   G * 0.587   B * 0.114   (1 - A || 0) * 255;
    return brightness > 186 ? '#000000' : '#FFFFFF';
  }
  getContrastColor(...numberColor);

CodePudding user response:

split makes no guarantees about how many pieces it'll output at runtime. Passing a string like "foo" would make your routine fail, because your function would not return a valid 4-tuple.

You could use something like this, which guarantees a proper tuple output:

function getNumberTuple(color: string) : [number, number, number, number?] {
  const rgba = color.substring(5, color.length - 1).replace(/ /g, "")
  const numbers = rgba.split(",").map((item) => Number(item));
  return [numbers[0] || 0, numbers[1] || 0, numbers[2] || 0, numbers[3]]
}

function getContrastColor(R: number, G: number, B: number, A?: number) { /* ... */}

getContrastColor(...getNumberTuple("color 123,123,123"));

CodePudding user response:

How about using tuples?

const numberColor = [255,50,50,0.1]

// Check RGBA
function getContrastColor([ R, G, B, A ]:[number, number, number, number]) {
  const brightness = R * 0.299   G * 0.587   B * 0.114   (1 - A) * 255;

  return brightness > 186 ? '#000000' : '#FFFFFF';
}

// function call with spread operator 
getContrastColor(numberColor);
  •  Tags:  
  • Related