Open
Description
I made this type because I wanted a type safe way to pull properties from an object via a path, and I thought it might be useful to this library. I chose to make any properties not found in the object never, but you could use unknown to keep current functionality if you wanted. Just thought I'd share.
type TakeProp<T extends string> = T extends `${infer Prop}/${string}` ? Prop : never
type TakeRest<T extends string> = T extends `${string}/${infer Rest}` ? Rest : T
type PathExtract<Value, Path extends string> =
TakeProp<Path> extends never //if path type is not a path, get the prop from Value
? Path extends keyof Value
? Value[Path]
: never
: TakeProp<Path> extends keyof Value //check if prop is in value
? PathExtract<Value[TakeProp<Path>], TakeRest<Path>> //recurse
: never //failure
const num: number = PathExtract<{a: {b: number}}, "a/b">
This currently does not cover ~0 and ~1 but i think with a little more work that could be figured out.
Metadata
Metadata
Assignees
Labels
No labels