In my attempt to create a robust typing interface for a hashmap in typescript,
The hashmap consists of a key with a dynamic string name, and a values
array containing a Generic type.
I attempted to define the interface as follows:
export interface DynamicHashmap<T> {
[dynamicKey: string]: string;
values: T[];
}
However, it fails to compile and continues to raise an error:
[ts] Property 'values' of type 'T[]' is not assignable to string index type 'string'.
For instance, the generated value corresponding to this type groups values based on an object attribute (in this case, User.group
). The dynamicKey
is resolved as group
.
const user1: User = { id: 'userValue1', group: 'someGroupId' };
const user2: User = { id: 'userValue2', group: 'someGroupId' };
const result = {
group: 'someGroupId',
values: [
{ id: 'userValue1', group: 'someGroupId' },
{ id: 'userValue2', group: 'someGroupId' }
]
}
I suspect that the static values
property is conflicting with the dynamic key.
How can I achieve the desired level of strong typing in this scenario?