groupBy是TypeScript安全的 [英] groupBy that is TypeScript safe
问题描述
给出所有已经存在的答案,我们尝试创建一个不抱怨TypeScript错误的 groupBy
箭头函数.在
使用的键
确实有可能为空/空白.因此,TypeScript在这里并没有错.因此,在那种情况下,它应该简单地使用占位符,例如 NA
或类似的东西.
为此 groupBy
函数创建可重用的无错误打字稿版本的正确方法是什么?
使用一些泛型来降低键类型并强制对象包含键:
type ObjectKey =字符串|编号|象征;const groupBy =< K扩展ObjectKey,TItem扩展Record< K,ObjectKey>>(项目:TItem [],键:K):Record< ObjectKey,TItem []>=>items.reduce((结果,项目)=>({...结果,[item [key]]:[...(结果[item [key]] || []),项目],}),{}作为Record< ObjectKey,TItem []>);
Given all the answers already out there we tried to create a groupBy
arrow function that doesn't complain about TypeScript errors. with guidance from this answer and this one we already have this working code:
const groupBy = <TItem>(
items: TItem[],
key: string
): { [key: string]: TItem[] } =>
items.reduce(
(result, item) => ({
...result,
[item[key]]: [...(result[item[key]] || []), item],
}),
{}
)
It is indeed possible that the used key
is empty/blank. So TypeScript is not wrong here. So in that case it should simply use a placeholder value like NA
or something.
What is the correct way to create a reusable error free typescript version for this groupBy
function?
Use some generics to lower down the key type and force the object to contain the key:
type ObjectKey = string | number | symbol;
const groupBy = <K extends ObjectKey, TItem extends Record<K, ObjectKey>>(
items: TItem[],
key: K
): Record<ObjectKey, TItem[]> =>
items.reduce(
(result, item) => ({
...result,
[item[key]]: [...(result[item[key]] || []), item],
}),
{} as Record<ObjectKey, TItem[]>
);
这篇关于groupBy是TypeScript安全的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!