
Useful TypeScript generics for tree structures
Developers are surrounded by hierarchies of objects, such as the DOM tree, React component tree, and NPM dependency tree. Tree-like data structures are quite common in code, and reliable Typescript types make working with them more confident. In this article, I want to share with you some generics that benefit me the most. Deep partial Sometimes we are willing to provide default values for all parameters of a third-party function, even nested ones, so they are all optional. In that case DeepPartial type is helpful: type DeepPartial < T > = T extends object ? { [ P in keyof T ]?: DeepPartial < T [ P ] > ; } : T ; type InitialType = { header : { size : ' sm ' | ' md ' | ' lg ' ; color : ' primary ' | ' secondary ' ; nav : { align : ' left ' | ' right ' ; fontSize : number ; } }; footer : { fixed : boolean ; links : { max : 5 | 10 ; nowrap : boolean ; } } }; type ResultType = DeepPartial < InitialType > ; /* type ResultType = { header?: { size?: "sm" | "md" | "lg" | undefined; color?: "pr
Continue reading on Dev.to
Opens in a new tab




