简体   繁体   中英

Typescript type errors in Reduce Function

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;
}, []);

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)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM