This function
function abc<K extends keyof any>(
param: K,
) {
const z: { [p in K]: string } = {
[param]: 'abc',
};
}
gives the following error:
TS2322: Type '{ [x: string]: string; }' is not assignable to type '{ [p in K]: string; }'.
Isn't something like this possible in typescript? I'm using Typescript 4.3.5
Thanks
José
You are getting this error, because TS is unsure about
Kgeneric parameter. It is a black box for compiler.See this example:
keyof anyis the same as built inPropertyKey. Also,PropertyKeyis a union type, henceKmight be a union as well.Consider above example.
Kis a42 | 'prop' | symbolwhich is perfectly valid type and meets the requirement.Because
Kis a union, in theoryzshould be{ [p in 42 | 'prop' | symbol]: string }, right? So we should get an object with three properties? But you have provided only one.Again, because
Kis a black box for TS compiler it is unsafe to make any assumptions.Related answer