I am currently having some trouble understanding Typescript Mapped Types, where they list that "Key remapping" is possible, but when actually trying that with a array, it just errors with Type '"key"' cannot be used to index type 'A[E]'.
Note: this is a types question, not a runtime question.
Example Code:
interface ListEntry {
key: string;
prop: string;
}
type MapListEntryArrayToRecord<A extends ListEntry[]> = {
// Error "Type '"key"' cannot be used to index type 'A[E]'"
[E in keyof A as A[E]['key']]: A[E]['prop'];
};
const input: ListEntry[] = [
{ key: 'key1', prop: 'Prop1' },
{ key: 'key2', prop: 'Prop2' },
];
function someFunction<List extends ListEntry[]>(list: List): MapListEntryArrayToRecord<List> {
// some implementation
const ret: Record<string, ListEntry['prop']> = {};
for (const { key, prop } of list) {
ret[key] = prop;
}
return ret as MapListEntryArrayToRecord<List>;
}
const mapped = someFunction(input);
// expecting intellisense for all available keys
mapped;
// example of what i would expect
const expectedOutput = {
key1: 'Prop1',
key2: 'Prop2',
};
// expecting intellisense for all available keys
expectedOutput;
PS: i tried to search for a answer, but could not find any typescript examples on how to do this.