Home > Enterprise >  Extract the type of the component props in react-storybook with typescript
Extract the type of the component props in react-storybook with typescript

Time:10-18

I am working on a component in the story book and here is how it looks:

  import React, { useCallback } from 'react';
  import { ButtonProps } from './types';

  const Button = (props: ButtonProps) => {
  // Destructre the needed props to be used across the component
  const { children, extraClasses, onClick } = props;
  // Memoize the onClick function so it is not recreated upon
  // each re-render
  const memoizedOnClick = useCallback(() => onClick?.(props), []);
  return (
    <button className={extraClasses} onClick={memoizedOnClick}>
      {children}
    </button>
  );
};

Button.defaultProps = {
  children: <b>Test Button</b>
};

export default Button;

What I want now is extract the type of the props (ButtonProps) from the component itself so I can use it in another interface. I have tried the following line but it always says type is any:

type DefaultButtonProps = React.ComponentProps<typeof Button>

Any help why the type DefaultButtonProps is always any while I declared it as following:

export interface ButtonProps extends HTMLButtonElement {
  children: ReactNode,
  extraClasses?: string;
  onClick?: (props: ButtonProps) => void
}

Thanks in advance.

CodePudding user response:

I tried your implementation of DefaultButtonProps, It was ButtonProps, not any.

Anyway, you can also test the following:

type DefaultButtonProps = Parameters<typeof Button>[0]
  • Related