![](/img/trans.png)
[英]Typescript 'keyof InstanceType<T>' cannot be used to index type error
[英]T[keyof T] cannot be used to index {}
我正在嘗試通過算法從最有效的方法到 groupby 在對象數組上實現一個有效的分組,並嘗試放置類型。 但我得到了錯誤:
T[keyof T] cannot be used to index {}
這是我的嘗試
static groupBy<T>(xs:T[], key: keyof T) {
return xs.reduce((rv, x)=> {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
rv: any
rv 都將是any 。
class A {
static groupBy<T>(xs: T[], key: keyof T) {
return xs.reduce((rv: any, x) => {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
}
}
如何使用它:
interface Person {
name: string;
age: number;
salary: number;
}
const data: Person[] = [
{name:"deepak", age: 30, salary: 2000},
{name:"deepak1", age: 32, salary: 1000},
{name:"deepak", age: 29, salary: 3000}
]
class A {
static groupBy<T>(xs: T[], key: keyof T) {
return xs.reduce((rv: any, x) => {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
}
}
console.log(A.groupBy(data, "name"))
Lodash的定義:
groupBy(
predicate?: Lodash.ListIterator<T, boolean> | Lodash.DictionaryIterator<T, boolean> | string,
thisArg?: any,
): Lodash.Dictionary<T[]>;
groupBy<R extends {}>(predicate?: R): Lodash.Dictionary<T[]>;
同步組返回 object 和 object 不能將任何其他元素作為鍵,而不是字符串|數字。 否則,您可以遵循更多通用解決方案。
interface Any<T> {
[key: string]: T[];
}
interface SMap<T> {
[key: string]: T;
}
class A {
static groupBy<T extends SMap<string>>(xs: T[], key: keyof T) {
return xs.reduce((rv: Any<T>, x) => {
if (!rv[x[key]]) {
rv[x[key]] = [];
}
rv[x[key]].push(x);
return rv;
}, {});
}
}
如果您不想使用any
,則需要正確定義類型以告訴 reducer 可以組合數據。
function groupBy<T extends {[LK in K]: keyof any}, K extends keyof T>(xs:T[], key: K) {
return xs.reduce<{[LK2 in T[K]]?: Array<T>}>((rv, x) => {
(rv[x[key]] = rv[x[key]] || [])?.push(x);
return rv;
}, {});
};
const result = groupBy([{ test: 'key' }], 'test');
result.key?.length; // 1
T 是 object,其中傳遞的密鑰類型是可以用作密鑰的東西(對於 rv)。
對於減速器 - 它以空 object 開頭 - 我們需要說結果將是 object ,其中鍵的值是來自 xs {[LK2 in T[K]]?: Array<T>}
的實體數組
沒有原版那么短。 但是,它不使用“any”或“as”強制轉換。 它還支持組鍵的任何數據類型,因此是未知的。
export function groupBy<T>(xs: T[], key: keyof T): Map<unknown, T[]> {
return xs.reduce((rv: Map<unknown, T[]>, entity: T) => {
const value = entity[key];
if (rv.has(value)) {
rv.get(value)?.push(entity)
} else {
rv.set(value, [entity]);
}
return rv;
}, new Map());
};
用法示例:
const badgesByTypes = groupBy(currentState.badges, 'type');
for (const [key, values] of badgesByTypes.entries()) {
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.