Is there a way in my typescript function to ensure that all keys in the second argument belong to the object defined by the first argument?
For example:
mapTo([new KeyValue('a', 'b'), new KeyValue('x', 'y')], {key: {key2: 1}});
In this scenario, all keys in the second argument (key and key2) must match the keys defined in the KeyValue object.
Here is the definition of the KeyValue class:
class KeyValue {
key: string;
key2: string;
constructor(k, k2) {
this.key = k;
this.key2 = k2;
}
}
Like so:
mapTo([new KeyValue('a', 'b')], {key: {key2: 1}}); -> valid
mapTo([new KeyValue('a', 'b')], {key: {key3: 1}}); -> invalid // key3 does not exist
To achieve this, I have implemented the mapTo function as follows:
public nest<T, K extends keyof T, K2 extends keyof T>(arr: [T], basis: {[k in K]: {[k2 in K2]}}) {
console.log('Hello!!!');
console.log(basis);
}
The code works perfectly, but if I add another key to the KeyValue class and use it in the arguments like this:
mapTo([new KeyValue('a', 'b' ,'c')], {key: {key2: {key3: 1}}});
And update the KeyValue class definition:
class KeyValue {
key: string;
key2: string;
key3: string;
constructor(k, k2, k3) {
this.key = k;
this.key2 = k2;
this.key3 = k3;
}
}
Then, the previously implemented function will not validate the third key. How can I adjust the function to accept dynamically nested values and still work perfectly?
Additional examples:
mapTo([new KeyValue('a', 'b' ,'c')], {key: 1}); -> valid
mapTo([new KeyValue('a', 'b' ,'c')], {key: {key1:1}}); -> valid
mapTo([new KeyValue('a', 'b' ,'c')], {key1: {key:1}}); -> valid
mapTo([new KeyValue('a', 'b' ,'c')], {key1: {key:{key3:1}}}); -> valid
mapTo([new KeyValue('a', 'b' ,'c')], {key1: {key:{key4:1}}}); -> invalid // key4 does not exist
mapTo([new KeyValue('a', 'b' ,'c')], {key3: {key2:0}}); -> valid