Last active
June 24, 2022 06:56
-
-
Save vimanvh/a8ca22fc887d5fb72e02f5db968d34aa to your computer and use it in GitHub Desktop.
Ukázka typování cesty v objektu libovolné úrovně
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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