Skip to content

Instantly share code, notes, and snippets.

@Belphemur
Last active October 30, 2020 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Belphemur/09157406a9b39ee9f6e0041d91241a55 to your computer and use it in GitHub Desktop.
Save Belphemur/09157406a9b39ee9f6e0041d91241a55 to your computer and use it in GitHub Desktop.
Deep generate dot notation in TypeScript with example
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