Issue
This is not working because Item[Key] can be anything and I want to restrict key be either a string or a number. Errors are highlighted with ** and it says: Type does not satisfy the constraint string | number | symbol
function groupBy<
Item,
Key extends keyof { [T in keyof Item]: Item[T] extends PropertyKey ? Item[T] : never}
>(items: Item[], key: Key): Record<**Item[Key]**, Item>{
const groups = {} as Record<**Item[Key]**, Item>;
for(const item of items){
groups[item[key]] = {
...groups[item[key]],
...item
};
}
return groups;
}
I also tried this but then i get this other error when I call the function, with the second parameter as 'name': Object literal may only specify known properties, and 'id' does not exist in type 'Record<"name", PropertyKey>'.
function groupBy<
Item extends Record<Key, PropertyKey>,
Key extends keyof Item
>(items: Item[], key: Key): Record<Item[Key], Item>{
const groups = {} as Record<Item[Key], Item>;
for(const item of items){
groups[item[key]] = {
...groups[item[key]],
...item
};
}
return groups;
}
Expected results:
groupBy([
{id: 1, name: 'Marc', isAlive: false },
{id: 1, age: 21 },
], 'isAlive'); //Should give me a type error
groupBy([
{id: 1, name: 'Marc', isAlive: false },
{id: 1, age: 21 },
], 'id'); //Should work
groupBy([
{id: 1, name: 'Marc', isAlive: false },
{id: 1, age: 21 },
], 'name'); //Should work
groupBy([
{id: 1, name: 'Marc', isAlive: false },
{id: 1, age: 21 },
], 'age'); //Should work
Solution
Okay I found the solution combining multiple solutions on here:
type KeysMatching<Item, Prop> = {
[Key in keyof Item]-?: Item[Key] extends Prop ? Key : never
}[keyof Item]
function groupBy<
Item extends Record<Key, PropertyKey>,
Key extends KeysMatching<Item, PropertyKey>
>(items: Item[], key: Key): Record<Item[Key], Item>{
const groups = {} as Record<Item[Key], Item>;
for(const item of items){
groups[item[key]] = {
...groups[item[key]],
...item
};
}
return groups;
}
groupBy([
{id: 1, name: 'Marc', isAlive: false },
{id: 1, age: 21, isAlive: true },
], 'isAlive'); //Should give me a type error
groupBy([
{id: 1, name: 'Marc', isAlive: false },
{id: 1, age: 21 },
], 'id'); //Should work
groupBy([
{id: 1, name: 'Marc', isAlive: false },
{id: 1, name: 'Marc',age: 21 },
], 'name'); //Should work
groupBy([
{id: 1, age: 21,name: 'Marc', isAlive: false },
{id: 1, age: 21 },
], 'age'); //Should work
Answered By - mgm793
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.