groupBy是TypeScript安全的 [英] groupBy that is TypeScript safe

查看:81
本文介绍了groupBy是TypeScript安全的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出所有已经存在的答案,我们尝试创建一个不抱怨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],
    }),
    {}
  )

However, it still complains: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'.
No index signature with a parameter of type 'string' was found on type 'unknown'.

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

Playground link

这篇关于groupBy是TypeScript安全的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆