I have the following typescript function (simplified for this question):
function assign<T1,T2>(o1:T1,k1:keyof T1, o2:T2, k2:keyof T2){ o1[k1] = o2[k2];}
I want to ensure that the data type of o1[k1]
is the same as that of o2[k2]
. Meaning that the function will only allow combinations of property names where assignments of the values will be possible. Example:
let a = {foo: 'hello', version: 10};let b = {bar: 'bye'};assign(a, 'foo',b, 'bar'); // This should be allowed as both properties are stringsassign(a, 'version',b, 'bar'); // This should give a type error as the properties have different types
I tried using mapped types etc. but was not able to find a correctly working solution.For example:
function assign<T1,T2>(o1:T1,k1:keyof T1, o2:T2, k2:T1[K1] extends T2[K2]?keyof T2:never){ o1[k1] = o2[k2];}
But that does not work. Any ideas?