Is it possible to type an array of strings in such a way that the array can only be a valid property path in a given object? The type definition should work for all deeply nested objects.
Example:
const object1 = {
someProperty: true
};
const object2 = {
nestedObject: object1,
anotherProperty: 2
};
type PropertyPath<Type extends object> = [keyof Type, ...Array<string>]; // <-- this needs to be improved
// ----------------------------------------------------------------
let propertyPath1: PropertyPath<typeof object1>;
propertyPath1 = ["someProperty"]; // works
propertyPath1 = ["doesntExist"]; // should not work
let propertyPath2: PropertyPath<typeof object2>;
propertyPath2 = ["nestedObject", "someProperty"]; // works
propertyPath2 = ["nestedObject", "doesntExist"]; // should not work
propertyPath2 = ["doesntExist"]; // should not work
Aucun commentaire:
Enregistrer un commentaire