Last active
September 14, 2020 12:35
-
-
Save Soul-Master/633c03ffc77c13a29909199fb25bf37b to your computer and use it in GitHub Desktop.
Strongly-typed deep path
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
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'); |
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 Foo { | |
bar(): void; | |
} | |
type AsyncType<T> = { | |
[P in keyof T & string as `${P}Sync` | `${P}Async`]: T[P] | |
}; | |
var x: AsyncType<Foo>; |
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
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