Sorry about the vague wording of the question.
Let's say I have a type like this:
type TestObject = {
arr: Array<{x: number, y: Array<{z: string}}>>;
obj: {[key: string]: number;
}
I'd like to be able to enforce that paths are valid - ideally at compile time, but runtime would be okay, along these lines:
function setValue<T>(object: T, path: string, value: unknown) {
// perform the set operation
}
My intention is that the following should work:
const o: TestObject = { arr: [], obj: {} };
setValue<TestObject>(o, "arr[0].x", 1);
setValue<TestObject>(o, "arr[0].y[2].z", "hello world");
setValue<TestObject>(o, "obj['x']", 1);
But if you tried this, it should fail, as there is no TestObject.a
:
setValue<TestObject>(o, "a", 1);
Ideally this would be implemented in such a way that the developer would get Intellisense and errors in the IDE, but a runtime solution would be okay as well.