I have developed a detailed use-case and created an MCVE to showcase it:
function createSeedMap<T extends (...args:any)=>any>(seedKey:keyof T, seedValue:string):void {
// ...
const seedMap:Record<keyof T, string> = {
[seedKey]: seedValue,
};
// ...
}
The crucial element here is the seedMap
variable, as the function serves to illustrate the problem at hand.
In this scenario, I have a variable called seedKey
with a type of keyof T
. This variable acts as a dynamic property in an object initializer assigned to a variable named seedMap
, which is typed as Record<keyof T, string>
.
It is essential for other sections of my code (not shown) that the type of the seedKey
variable remains as keyof T
. Changing these types would require numerous type assertions, which I prefer to avoid.
Despite what seems like a straightforward setup, I encountered the following error:
Type '{ [x: string]: string; }' is not assignable to type 'Record<keyof T, string>'.
For reasons I don't fully grasp, the TypeScript compiler interprets my keyof T
as a string
in the object initializer. The issue arises when trying to assign an object with a string index to a Record with a keyof T
index (where seedKey
could potentially be a symbol!).
Initially, I attempted to address this by modifying the code as follows:
function createSeedMap<T extends (...args:any)=>any>(seedKey:keyof T, seedValue:string):void {
// ...
const seedMap:Record<keyof T, string> = {};
seedMap[seedKey] = seedValue;
// ...
}
However, this led to a new error:
Type '{}' is not assignable to type 'Record<keyof T, string>'.
At this point, I suspect that using keyof T
as an index for Record
may introduce unsupported scenarios.
I've searched for information on this limitation and potential workarounds without resorting to type assertions, but I haven't found a satisfactory solution yet. The related Q/A's I discovered did not seem to directly address this specific issue or remain unanswered:
- Typescript generic type - Type 'keyof T1' cannot be used to index type
- How to declare a "Record" type with partial of specific keys in typescript?
- TypeScript: Indexing into an object type using keyof
- keyof T doesn't appear as a string subtype within mapped types
Any insights or suggestions would be highly appreciated.
I am running TypeScript 4.8.4 and haveconfirmed these issues in the TS Playground, eliminating any local configuration discrepancies.