Skip to content

Instantly share code, notes, and snippets.

@Belphemur

Belphemur/DeepDotKey.ts

Last active Oct 30, 2020
Embed
What would you like to do?
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