我收到一个类型错误,我不知道如何正确构建界面
const data = [
{ category: 'fish', age: 10, color: 'red' },
{ category: 'fish', age: 9, color: 'red' },
{ category: 'fish', age: 8, color: 'blue' },
{ category: 'fish', age: 7, color: 'blue' },
{ category: 'birds', age: 10, color: 'red' },
{ category: 'birds', age: 9, color: 'red' },
{ category: 'birds', age: 8, color: 'blue' },
{ category: 'birds', age: 7, color: 'blue' },
];
interface CountProps {
category: string;
age: number;
color: string;
}
const count = (dataToCount: CountProps) => {
return dataToCount.reduce((t, v) => {
const f = t.find((i) => i.category === v.category);
if (f) f.total++;
else t.push({ category: v.category, total: 1 });
return t;
}, []);
};
const summary = count(data);
Run Code Online (Sandbox Code Playgroud)
我得到的错误是Property 'reduce' does not exist on type 'CountProps'.ts(2339),我不知道 t,v,a 应该是什么类型。
的.reduce()是一个数组原型,但是CountProps是一个对象。我相信您实际上是指要传递给 count 函数的对象数组:
const count = (dataToCount: CountProps[]) => {
// Rest of the logic here
}
Run Code Online (Sandbox Code Playgroud)
您还需要声明累加器的类型,因为 TypeScript 无法推断其类型。
选项 1:在回调中声明类型
return dataToCount.reduce((t: Array<{ category: string, total: number }>, v) => {
// Reduce logic here
}, []);
Run Code Online (Sandbox Code Playgroud)
选项 2:在源数组中声明类型
return dataToCount.reduce((t, v) => {
// Reduce logic here
}, [] as Array<{ category: string, total: number }>);
Run Code Online (Sandbox Code Playgroud)
概念验证代码:
const data = [
{ category: 'fish', age: 10, color: 'red' },
{ category: 'fish', age: 9, color: 'red' },
{ category: 'fish', age: 8, color: 'blue' },
{ category: 'fish', age: 7, color: 'blue' },
{ category: 'birds', age: 10, color: 'red' },
{ category: 'birds', age: 9, color: 'red' },
{ category: 'birds', age: 8, color: 'blue' },
{ category: 'birds', age: 7, color: 'blue' },
];
interface CountProps {
category: string;
age: number;
color: string;
}
const count = (dataToCount: CountProps[]) => {
return dataToCount.reduce((t: Array<{ category: string, total: number }>, v) => {
const f = t.find((i) => i.category === v.category);
if (f) f.total++;
else t.push({ category: v.category, total: 1 });
return t;
}, []);
};
const summary = count(data);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
486 次 |
| 最近记录: |