Greetings and thank you for your help in advance.
I am currently working on creating a UI component that accepts boolean and string style props. However, I encountered an error related to the Styles
type which includes the bg
prop that accepts a string
. I have tried different approaches to resolve this using a Record
type, but it did not prove helpful as the issue arises at runtime.
The specific error points to
stylesProps[k as keyof StyleProps]
. What would be considered the best practice to tackle this error?
Furthermore, is there a more efficient method than using an array of keys for looping through expected key types? Currently, updating the code in two locations when adding more properties seems cumbersome, so I aim to streamline it into a single location.
"Type 'string | boolean | undefined' is not assignable to type 'undefined'.
Type 'string' is not assignable to type 'undefined'.ts(2322)"
// .tsx
// styles props
const keys = ["block", "center", "row", "column", "border", "bg"];
type Styles = {
block: boolean;
center: boolean;
row: boolean;
column: boolean;
border: boolean;
bg: string;
};
type AllowedStyles = Partial<Styles>;
// component props
type Props = Partial<
AllowedStyles & { children: JSXElement | JSXElement[] | undefined }
>;
// utilities
// this function will take in component props and return an object containing just the [k,v] of style props
const getBoxStyleProps = (props: Props): AllowedStyles => {
let stylesProps: AllowedStyles = {};
for (let k of keys) {
stylesProps[k as keyof AllowedStyles] = props[k as keyof AllowedStyles];
// ^-----------------------------------^ TS err
}
return stylesProps;
};
// more code, not included
//.jsx using component here with allowed style props
export default function Index() {
return (
<Box block column border bg="blue">
</Box>
);
}