i am a free programmer and recently learning about Typescript, more specifically i am experimenting with writing some code to get the value/typeof of any value inside a json object based on the path string, supporting correct pathing. Here is mine
My object looklike:
const my_user = {
id: 201,
name: 'Join Doe',
married: false,
details: {
phone: '+0123-456-789',
address: 'st12, RickRoll Street',
},
}
My type Key that help to make an correct string path of every value in the object:
type Key<O extends object> = { [K in keyof O]: O[K] extends undefined ? never : O[K] extends object
? `${K & string}.${Key<O[K]>}`
: `${K & string}`
}[keyof O]
My type Vlu that return type of the value with a correct string path
type Vlu<O extends object, P extends string> = P extends keyof O ? O[P] : P extends `${infer K}.${infer Rest}`
? K extends keyof O
? O[K] extends object
? Vlu<O[K], Rest>
: never
: never
: never
And then i have a fn to read object like this
(wrong path will mark as red by typescript, orelse return the value with it type)
const get = <O extends object, P extends Key<O>>(obj: O, paths: P): Vlu<O, P> => {
const rs = paths.split('.').reduce((obj, path) => obj[path], obj as any);
console.log(paths, rs, typeof rs)
return rs
}
Everything is great so far, but i realized i am not done yet, an object can be an Array and can contain an Array, i have no idea for this.
(there is no path
for an item in array, cant using index, if the elements in the array are not of the same type, … etc)
Sorry if my question is not clear and my bad eng but if you understand then can u give me some idea, i very appreciated.