Apologies for the unclear wording of the question.
Imagine having a data structure like this:
type ExampleObject = {
arr: Array<{x: number, y: Array<{z: string}>}>;
obj: {[key: string]: number};
}
I want to ensure that paths are valid - preferably at compile time, but runtime validation would also suffice. Here's an example of what I have in mind:
function setValue<T>(object: T, path: string, value: unknown) {
// perform the set operation
}
The goal is for the following to be achievable:
const o: ExampleObject = { arr: [], obj: {} };
setValue<ExampleObject>(o, "arr[0].x", 1);
setValue<ExampleObject>(o, "arr[0].y[2].z", "hello world");
setValue<ExampleObject>(o, "obj['x']", 1);
If you were to attempt something like this, it should fail, since there is no ExampleObject.a
:
setValue<ExampleObject>(o, "a", 1);
An ideal implementation would provide Intellisense and IDE error detection for developers, but a runtime resolution would suffice as well.