You are getting this error, because TS is unsure about K
generic parameter. It is a black box for compiler.
See this example:
function abc<K extends PropertyKey>(
param: K,
) {
const z: { [p in K]: string } = {
[param]: 'abc',
};
return z
}
const result2 = abc<42 | 'prop' | symbol>('prop')
keyof any
is the same as built in PropertyKey
. Also, PropertyKey
is a union type, hence K
might be a union as well.
Consider above example. K
is a 42 | 'prop' | symbol
which is perfectly valid type and meets the requirement.
Because K
is a union, in theory z
should 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 K
is a black box for TS compiler it is unsafe to make any assumptions.
Related answer