1

How to create a typescript with multiple keys, some of which are expressed as computed key with a generic value;

E.g.

{
groupName: 'Group 1',
participant1Id: {firstName: string, lastName: string, ...}
participant2Id: {firstName: string, lastName: string, ...}
...
}

cannot be expressed as

type Group<T> = {
  groupName: string;
  [key: string]: T;
};


due to **Property 'groupName' of type 'string' is not assignable to 'string' index type 'T'**
Damjan Vučina
  • 352
  • 2
  • 12
  • Is there any commonality to the "computed"/"generic" keys? Do they all match `\`participant${number}Id\``? Or are the completely arbitrary? This could be the difference between "yes this is easy" or "no TS doesn't support this very well" – jcalz Jan 19 '23 at 15:50
  • There isn't those are uuids. – Damjan Vučina Jan 19 '23 at 17:23
  • Then the issue is discussed [in this q/a](https://stackoverflow.com/q/61431397/2887218); note the caveats around `{[k: string]: X} & {prop: Y}` mentioned there. – jcalz Jan 19 '23 at 18:57

1 Answers1

1

You can do this:

type Group<T> = {
  [key: string]: T;
} & { groupName: string; };
thedude
  • 9,388
  • 1
  • 29
  • 30
  • haha great idea, that's so funny that it's able to digest this format, but not the one it the OP. thanks @thedude – Damjan Vučina Jan 19 '23 at 17:28
  • This sort of works but you will find it difficult to create a new value of type `Group`; see [this q/a](https://stackoverflow.com/q/61431397/2887218) for more information. – jcalz Jan 19 '23 at 18:55
  • @jcalz you are correct, this does remove the ts error but I feel it'll end up biting me in the long run. Ended up refactoring the data structure so it's no longer an issue – Damjan Vučina Jan 21 '23 at 14:11