0

I would like to pass to a Provider an orientation value (horizontal or vertical), but I have it declared as optional in case the user does not want to pass it.

Through defaultProps I am trying to do the same that I could do with {orientation = 'horizontal'} but it's not working correctly.

This gives me an error where it says orientation can be undefined.

export interface TabsProps extends Props {
    active: string;
    color?: DanaColor;
    orientation?: 'horizontal' | 'vertical';
    onTabChange: (tabKey: string) => void;
    children: ReactElement | ReactElement[];
}

const defaultProps: Partial<TabsProps> = {
    orientation: 'horizontal',
};

export const Tabs = (props: TabsProps) => {
    const { children, ...context } = { ...defaultProps, ...props };

    return (
        <TabsProvider value={context}>
            <div css={tabs(context.orientation)}>
                <div css={tabList(context.orientation)} role="tablist">
                    {children}
                </div>
            </div>
        </TabsProvider>
    );
};

1 Answers1

2

That is because you are explicitly telling TypeScript that defaultProps can be undefined on instantiation (and all the other keys). Instead simply remove the explicit type and instead tell TypeScript this object is readonly (immutable) with the as const assertion

const defaultProps = {
    orientation: 'horizontal',
} as const;

Alternatively, explicitly pick the keys you want and set to Required

const defaultProps2: Required<Pick<TabsProps, 'orientation'>> = {
    orientation: 'horizontal'
}

See on TS Playground

Cody Duong
  • 2,292
  • 4
  • 18