When using a variable as an object key with generics, I encountered an issue where TypeScript does not allow assigning values from one object to another. In this scenario, I have two objects declared with some shared keys and some unique keys. I also have a function with a generic type that must be a key present in both objects.
Here are some conditions under which it works:
- If the object being assigned to does not have any unique keys.
- If all shared keys have the same type in both objects.
- When generics are not used.
For example:
// types declared here are not crucial, as long as they are not mutually assignable (with strictNullCheck: true)
type A = number;
type B = string;
type C = boolean;
type D = null;
type E = undefined;
type Test1 = {
a: A;
b: B;
c: C;
d: D;
};
declare const test1: Test1;
type Test2 = {
b: B;
c: C;
d: D;
e: E;
};
declare const test2: Test2;
function testFn<T extends keyof Test1 & keyof Test2>(t: T) {
test1[t] = test2[t];
// ^^^^^^^^
// Type 'Test2[T]' is not assignable to type 'Test1[T]'.
// Property 'a' is missing in type 'Test2' but required in type 'Test1'. ts(2322)
}
const key = 'b';
test1[key] = test2[key]; // works fine with keys b, c, d