Home > Mobile >  Typescript type errors in Reduce Function
Typescript type errors in Reduce Function

Time:07-22

I have two dummy functions using reduce method. The aim is to count how many characters have of each eye color and 2nd array of possible eye colors.

My point is that typescript gives an error in totalCounterColors on acc[color]:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'

and 2nd function totalUniqueColors:

Argument of type 'string' is not assignable to parameter of type 'never'.

I was trying different the type declaration and cast and still can get the problems solved. I am relatively new to typescript and want to understand what's the reasons behind as typescript errors quite cryptic for me. Thanks.

type Character = {
  name: string;
  eye_color: string;
  gender: string;
};

const characters: Character[] = [
  {
    name: 'Luke Skywalker',
    eye_color: 'blue',
    gender: 'male',
  },
  {
    name: 'Darth Vader',
    eye_color: 'yellow',
    gender: 'male',
  },
  {
    name: 'Anakin Skywalker',
    eye_color: 'blue',
    gender: 'male',
  },
];

const totalCounterColors = characters.reduce((acc, curVal) => {
  const color = curVal.eye_color as string;
  if (acc[color]) {
    acc[color]  ;
  } else {
    acc[color] = 1;
  }
  return acc;
}, {});

const totalUniqueColors = characters.reduce((acc, curVal) => {
  if (acc.indexOf(curVal.eye_color) === -1) {
    acc.push(curVal.eye_color);
  }
  return acc;
}, []);

CodePudding user response:

You need to tell TypeScript what type the empty accumulators are:

const totalCounterColors = characters.reduce((acc: Record<string, number>, curVal) => {
  const color = curVal.eye_color;
  if (acc[color]) {
    acc[color]  ;
  } else {
    acc[color] = 1;
  }
  return acc;
}, {});

const totalUniqueColors = characters.reduce((acc: string[], curVal) => {
  if (acc.indexOf(curVal.eye_color) === -1) {
    acc.push(curVal.eye_color);
  }
  return acc;
}, []);

or more succinctly

const totalCounterColors = characters.reduce((acc: Record<string, number>, {eye_color: color}) => {
  acc[color] = (acc[color] || 0)   1;
  return acc;
}, {});

const totalUniqueColors = Array.from(new Set(characters.map(c => c.eye_color)));
  • Related