Assuming I declare a Typescript interface to a very large, deep and complex object in a method like this:
interface DeepObject {
prop1: string;
prop2: {
prop3: string;
prop4: boolean;
prop5: {
prop6: Date;
};
};
}
I would like to write a function that sets a deep property on the object, while restricting the type of said property based on the accessor string. Here is an example of said function:
function setDeep(object: any, path: string, value: any): void {
const tags = path.split('.');
const length = tags.length - 1;
for (let i = 0; i < length; i++) {
if (object[tags[i]]) {
object = object[tags[i]];
} else {
return;
}
}
object[tags[length]] = value;
}
I could use the setDeep
function like this:
const myDeepObject: DeepObject = {
prop1: '',
prop2: {
prop3: '',
prop4: false,
prop5: {
prop6: new Date()
}
}
};
setDeep(myDeepObject, 'prop2.prop5.prop6', new Date(2002));
The problem in this example is the any
notations. I would like the setDeep
function to only accept an interface of DeepObject
for the first argument, and extrapolate from that interface and the string provided in argument 2, what the type should be for argument 3. Instead of just allowing anything to be set for argument 3. Is this possible?