Problem with Typescript interface and dynamic properties using generics

159 Views Asked by At

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é

1

There are 1 best solutions below

1
captain-yossarian from Ukraine On

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