【问题标题】:type problems with reducereduce 的类型问题
【发布时间】:2022-07-22 20:00:01
【问题描述】:

我有两个使用 reduce 方法的虚拟函数。目的是计算每种眼睛颜色和第二组可能的眼睛颜色有多少个字符。

我的意思是打字稿在 acc[color] 上的 totalCounterColors 中给出错误:

元素隐含地具有“任何”类型,因为类型的表达式 “字符串”不能用于索引类型“{}”

和第二个函数totalUniqueColors:

“字符串”类型的参数不能分配给类型参数 '从不'。

我尝试了不同的类型声明和强制转换,但仍然可以解决问题。我对打字稿比较陌生,想了解打字稿错误背后的原因对我来说非常神秘。谢谢。

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

【问题讨论】:

    标签: javascript typescript types


    【解决方案1】:

    你需要告诉 TypeScript 空累加器是什么类型:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-25
      • 2015-05-08
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多