Last active
October 30, 2020 22:47
-
-
Save Belphemur/09157406a9b39ee9f6e0041d91241a55 to your computer and use it in GitHub Desktop.
Deep generate dot notation in TypeScript with example
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
interface Hello { | |
foo : World; | |
bar: Number; | |
array: World[] | |
} | |
interface World { | |
greeting: string; | |
} | |
type DeepDotKey<T> = { | |
[P in keyof T]: DeepDotKey<T[P]>; | |
} & (() => string | number); | |
function deepDotKey<T>(sep: string = '.', prev?: string | number): DeepDotKey<T> { | |
return new Proxy<any>(() => prev, { | |
get: (_, next) => { | |
if (typeof next === "symbol") { | |
throw new Error("Cannot use symbols with deepDotKey."); | |
} | |
return deepDotKey(sep, prev ? `${prev}${sep}${next}` : next); | |
}, | |
}); | |
} | |
const _def = deepDotKey<Hello>(); | |
console.log(_def.foo.greeting()); | |
console.log(_def.array[0].greeting()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment