Skip to content

Instantly share code, notes, and snippets.

@Soul-Master
Last active September 14, 2020 12:35
Show Gist options
  • Save Soul-Master/633c03ffc77c13a29909199fb25bf37b to your computer and use it in GitHub Desktop.
Save Soul-Master/633c03ffc77c13a29909199fb25bf37b to your computer and use it in GitHub Desktop.
Strongly-typed deep path
type PropType<T, Path extends string> =
string extends Path ? never :
Path extends keyof T ? T[Path] :
Path extends `${infer K}.${infer R}` ? K extends keyof T ? PropType<T[K], R> : never : never;
declare function getPropValue<T, P extends string>(obj: T, path: P): PropType<T, P>;
const obj = {
a:
{
b:
{
c: 42,
d: 'hello'
}
}
};
// number
const c = getPropValue(obj, 'a.b.c');
// never
const xxx = getPropValue(obj, 'a.b.xxx');
interface Foo {
bar(): void;
}
type AsyncType<T> = {
[P in keyof T & string as `${P}Sync` | `${P}Async`]: T[P]
};
var x: AsyncType<Foo>;
type StringWithId<T extends string> = T extends `row_${infer _}` ? T : never;
declare function parseId<T extends string>(value: StringWithId<T>): void;
parseId("helloWorld"); // Error
parseId("row_one"); // Ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment