Skip to content

Instantly share code, notes, and snippets.

@vimanvh
Last active June 24, 2022 06:56
Show Gist options
  • Save vimanvh/a8ca22fc887d5fb72e02f5db968d34aa to your computer and use it in GitHub Desktop.
Save vimanvh/a8ca22fc887d5fb72e02f5db968d34aa to your computer and use it in GitHub Desktop.
Ukázka typování cesty v objektu libovolné úrovně
/**
* Generický typ pro cestu v objektu
*/
type PathOf<Object extends object, Value> = {
[Property in keyof Object & string]:
Object[Property] extends Value
? `${Property}`
: Object[Property] extends object
? `${Property}.${PathOf<Object[Property], Value>}`
: never
}[keyof Object & string];
/**
* Pomocný testovací typ
*/
interface Toy {
name: string;
}
/**
* Testovací typ obsahující vnořená pole
*/
interface Person {
firstName: string,
lastName: string,
single: boolean;
child: {
firstName: string,
lastName: string,
age: 5,
toy: Toy
}
}
/**
* Instance objektu pro testování
*/
const person: Person = {
firstName: "Vít",
lastName: "Heřman",
single: true,
child: {
firstName: "Anna",
lastName: "Heřmanová",
age: 5,
toy: {
name: "pandulak"
}
}
}
/**
* Ukázka deklarace cesty v danén objektu
*/
const path: PathOf<Person, string> = "firstName";
/**
* Funkce pro přístup k hodnotě iobjektu na základě typované cesty
*/
function getPathValue<Object extends object, Value>(obj: Object, path: PathOf<Object, Value>) {
const components = path.split(".");
let value = obj;
for (let component of components) {
value = value[component];
}
return value;
}
console.log(getPathValue<Person, string>(person, "child.toy.name"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment