React.forwardRef/Typescript defaultProps not working

We have a react component library for my own project. It was written in js (Customized material-ui library ;)) ). I have task to migrate components from js to ts, one by one.
Here is an example of component :

import * as React from 'react';
import classNames from 'classnames';

import Typography from '../Typography';

import styles from './link.scss';

type LinkPropTypes = {
    className: string,
    component: React.ElementType,
    children: React.ReactNode,
    color: 'error' | 'inherit' | 'initial' | 'primary' | 'secondary' | 'text-primary' | 'text-secondary',
    underline: 'none' | 'always' | 'hover',

};

const Link = React.forwardRef<HTMLElement, LinkPropTypes>((props, ref) => {
    const {
        color,
        component,
        underline ,
        className: classNameProp,
        ...restProps
    } = props;

    const className = classNames(
        styles[`link--underline-${underline}`],
        classNameProp,
    );

    return (
        <Typography
            className={className}
            color={color}
            component={component}
            ref={ref}
            {...restProps}
        />
    );
});

Link.displayName = 'Link';

Link.defaultProps  = {
    component: 'a',
    color: 'primary',
    underline: 'hover'
} ;
export default Link;

When I try to use this component in main app, it gives such error

<Link>asdasd</Link>

Type '{ children: string; }' is missing the following 
properties from type 'PropTypes': component, color, underline

But when I pass all props it works correctly:

<Link color="primary" underline="hover" component="a">asdasd</Link>

It asks for required parameters such as color, component, and underline. Even if they were in defaultProps.
I tried to assign defaultProps when destructuring props in component :

const {
        color = "primary",
        component = "a",
        underline ="hover",
        className: classNameProp,
        ...restProps
    } = props;

But storybook documentation can't recognize these defaultProps.
I don't want to duplicate defaultValues just for storybook documentation.

So my question is, is there any ways to assign defaultValues by Component.defaultProps in typescript??



Read more here: https://stackoverflow.com/questions/65839395/react-forwardref-typescript-defaultprops-not-working

Content Attribution

This content was originally published by Medet at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: