Created
November 6, 2018 04:10
-
-
Save Sammons/08d25aab42d258c1e8600eae39d3900e to your computer and use it in GitHub Desktop.
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
function AtPath<Target extends {}, Path1 extends keyof Target>(target: Target, path1: Path1): Target[Path1] | |
function AtPath<Target extends {}, Path1 extends keyof Target, Path2 extends keyof Target[Path1]>(target: Target, path1: Path1, path2: Path2): Target[Path1][Path2] | |
function AtPath<Target extends {}, Path1 extends keyof Target, Path2 extends keyof Target[Path1], Path3 extends keyof Target[Path1][Path2]>(target: Target, path1: Path1, path2: Path2, path3: Path3): Target[Path1][Path2][Path3] | |
function AtPath(target: {}, ...paths: string[]) { | |
let result = target as any; | |
for (let path of paths) { | |
result = result[path]; | |
if (result === void 0) { | |
return result; | |
} | |
} | |
return result; | |
} | |
// result is "blue", if we access a path that does not exist, it does not compile | |
const result = AtPath({ color: colors.blue }, 'color'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment