0

I've bumped into a situation when the usage of the keyof has a strange behavior.

Let's assume I have the next interface:

interface Data {
    someKey1: string,
    someKey2: number,
    someKey3: boolean
}

And I want to iterate over keys of an object which implements the interface and assign a value to a separate object.

    const data: Data = {...}; // it has the data inside
    const dataCopy: Partial<Data> = {};

    Object.keys(data).forEach((key: keyof Data) => {
      dataCopy[key] = this.data[key];
    });

The ts linter shows me the next error:

dataCopy[key] = this.data[key];
^
Type 'string | number | boolean' is not assignable to type 'never'.

But, if I will use the same logic but with generic, it will work.

Object.keys(data).forEach(<K extends keyof Data>(key: K) => {
  dataCopy[key] = this.data[key];
});

Question

Why is it actually happening? For me keyof K and <K extends keyof Data> are describing the same thing and should work the same in this case. Could anyone explain the behavior?

Tonnio
  • 574
  • 2
  • 9
  • But `(key: K)` still does not compile – captain-yossarian from Ukraine Nov 22 '21 at 10:48
  • There is a problem on the signature: `(key: keyof Data) => {` it says that `key` does not correspond to the expected type which is `string`. [Playground Link](https://www.typescriptlang.org/play?ssl=13&ssc=4&pln=7&pc=1#code/JYOwLgpgTgZghgYwgAgCJzHZBvAUMg5AZwHsBbCAaQgE8BGALmLClAHMAafQ0i6mgExMQAVzIAjaF0LFyVWgGYm4kiQA2EOCFwBfXPoAmEBGrhQUCEiCJhkBjHCbpMAbmQB6d8mC2AFnCJkMF8Ue0xva2AjXEtrWzC4AGESAAcaJgAFMzBgODUAHmc4AD5kAF4cHRd9AHlxACtjMAA6AGtaIgAKBIBKZpgSKABRRF9Ozvb05EmSGDQHHvLSvAIE5LSAbUmAXXKg32AiZoSt2m3qnR7qoA) – VLAZ Nov 22 '21 at 10:48
  • Related question: https://stackoverflow.com/questions/61671898/typescript-error-type-number-is-not-assignable-to-type-never not a duplicate, but the accepted answer there does explain why the non-generic function doesn't work. – kaya3 Nov 22 '21 at 10:53
  • https://stackoverflow.com/questions/67857960/how-to-selectively-assign-from-one-partial-to-another-in-typescript/67860407#67860407 – captain-yossarian from Ukraine Nov 22 '21 at 10:58

0 Answers0