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?