I am struggling with generating correct types for the genStruct function. Although I know how to make the function work, creating the right types has been challenging for me.
Below is the code snippet of my function:
type Breakpoint = "sm" | "md" | "lg"
export const genStruct = <T extends object>(
defaultValue: T,
breakpoints: Breakpoint[],
): Partial<Responsive<T>> => { // Using Partial to allow omission of keys
return breakpoints.reduce((acc, breakpoint) => {
acc[breakpoint] = Object.keys(defaultValue).length === 0
? ('' as any)
: { ...defaultValue }
return acc
}, {} as Partial<Responsive<T>>)
}
type NestedProps = {
rows: string
cols: string
}
type Responsive<T> = {
[key in Breakpoint]: T
}
type Default = Responsive<NestedProps>
const some_value: Default = {
sm: {
rows: '',
cols: '',
},
...genStruct({
rows: '',
cols: '',
}, ['md', 'lg'])
}
The TypeScript error message I'm receiving is as follows:
Type '{ sm: { rows: string; cols: string; }; md?: { rows: string; cols: string; } | undefined; lg?: { rows: string; cols: string; } | undefined; }' is not assignable to type 'Default'. Types of property 'md' are incompatible. Type '{ rows: string; cols: string; } | undefined' is not assignable to type 'NestedProps'. Type 'undefined' is not assignable to type 'NestedProps'.