I'm investing hours now, but don't want to give up :-)
I have an object, an target-path and a callback-function (with the "target-value" from the object)
This screenshot shows my wish
- a value and
- the correct type of this :-)
Do you have any Idea if this is possible?
I need the function param targetPath inside a type, see TARGET_PATH_AS_TYPE
Here is my current sourcecode:
type DotPrefix<T extends string> = T extends '' ? '' : `.${T}`
type DotNestedKeys<T> = T extends Date | any[]
? ''
: (
T extends object
? {
[K in Exclude<keyof T, symbol>]: `${K}${DotPrefix<
DotNestedKeys<T[K]>
>}`
}[Exclude<keyof T, symbol>]
: ''
) extends infer D
? Extract<D, string>
: never
type PropType<T, Path extends string> = string extends Path
? unknown
: Path extends keyof T
? T[Path]
: Path extends `${infer K}.${infer R}`
? K extends keyof T
? PropType<T[K], R>
: unknown
: unknown
type TestType = {
a: {
b: Date
c: number
d?: string
}
}
const myObject: TestType = {
a: {
b: new Date(),
c: 12
}
}
type MagicFunctionProps<T> = {
sourceObj: T
targetPath: DotNestedKeys<T>
render: (value: PropType<T, 'a.b' /* TARGET_PATH_AS_TYPE */>) => void
}
const magicFunction = <T>({
sourceObj,
targetPath,
render
}: MagicFunctionProps<T>): void => {
render(`${sourceObj}[${targetPath}] > logic comes later` as any)
}
magicFunction<TestType>({
sourceObj: myObject,
targetPath: 'a.b',
render: (value) => {
console.log(value)
}
})
DotNestedKeys: https://stackoverflow.com/a/68404823/8270748
PropTypes: https://github.com/microsoft/TypeScript/pull/40336
Thanks!!
Greetings crazyx13th