1

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é

ztp
  • 11
  • 3
  • 3
    Welcome to Stack Overflow! Please take the [tour] (you get a badge!), have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) I also recommend Jon Skeet's [Writing the Perfect Question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/). *"Isn't something like this possible in typescript?"* Something like what? It's not really clear from the code or question text/title what specifically you're trying to do. – T.J. Crowder Sep 28 '21 at 10:18

1 Answers1

0

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

  • 1
    I understand what you say, thank you. But I thought `param: K` could limit `K` to only one possibility. The problem might be that that constraint is not in the realm of static typing. – ztp Sep 30 '21 at 11:16