【发布时间】:2019-08-14 12:13:36
【问题描述】:
这个实现似乎运行良好 (Stackblitz):
/**
* Returns all the elements that are distinct by the
* `property` value. Note that the implementation uses a `Map<string, E>` to
* index the entities by key. Therefore the more recent occurences
* matching a key instance will overwrite the previous ones.
*
* @param property The name of the property to check for distinct values by.
* @param entities The entities in the array.
*
* @example
* ```
* let todos:Todo = [{ id: 1, "Lets do it!" }, {id: 2, "All done!"}];
* let dtodos:Todo[] = distinct<Todo>(todos, 'id');
*/
export function distinct<E>(entities:E[], property:string):E[] {
let map:Map<string, E> = new Map();
entities.forEach((e:E)=>{
map.set(e[property], e);
});
return Array.from(map.values());
}
唯一的一点是VSCode在e[property]部分下面画了一个红色的波浪线,错误信息是:
元素隐式具有“any”类型,因为类型“{}”没有索引 signature.ts(7017)
有没有办法摆脱它?
图书馆馆藏实施
我为这个轻量级的对象和实体状态管理器添加了最新的建议实现:
https://www.npmjs.com/package/@fireflysemantics/slice
npm i @fireflysemantics/slice
...
import {distinct} from '@fireflysemantics/slice/utilities';
演示
【问题讨论】:
标签: javascript node.js typescript slice