Skip to content

Instantly share code, notes, and snippets.

@ztrehagem
Last active September 26, 2023 01:58
Show Gist options
  • Save ztrehagem/9209d58acb2e01e1e4f73fa2a72fe42f to your computer and use it in GitHub Desktop.
Save ztrehagem/9209d58acb2e01e1e4f73fa2a72fe42f to your computer and use it in GitHub Desktop.
export class KeyPath<T extends string = string> {
#_brand!: never;
readonly #path: readonly string[];
constructor(path: T) {
this.#path = path.split(".");
}
of<Expected>(object: unknown): Expected {
for (const key of this.#path) {
if (object == null) {
break;
}
object = (object as Record<string, unknown>)[key];
}
return object as Expected;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment