我有一个 counts
函数,它接受一个元素数组并返回每个唯一项的计数,例如 uniq -c
:
counts(['a', 'b', 'a']) // => {a: 2, b: 1}
以下实现有效但违反了 prefer-reduce-type-parameter rule:
// Works with eslint warning
function counts<K extends number | string | symbol>(els: K[]): Record<K, number> {
return els.reduce((acc, cur) => {
acc[cur] = acc[cur] ? acc[cur] + 1 : 1
return acc
}, {} as Record<K, number>)
}
但是,当我删除强制转换并向 reduce
添加类型参数时,我收到一个错误:
// Fails with
// error TS2322: Type 'K' is not assignable to type 'Record<K, number>'.
// Type 'string | number | symbol' is not assignable to type 'Record<K, number>'.
// Type 'string' is not assignable to type 'Record<K, number>'.
// error TS2345: Argument of type '{}' is not assignable to parameter of type 'Record<K, number>'.
function counts<K extends number | string | symbol>(els: K[]): Record<K, number> {
return els.reduce<Record<K, number>>((acc, cur) => {
acc[cur] = acc[cur] ? acc[cur] + 1 : 1
return acc
}, {})
}