类型不可分配给类型 |同时学习打字稿和故事书

Type is not assignable to type | Learning type script and story book at the same time

我已经设置了 Story book,并且正在尝试将默认按钮组件从 JS 转换为 TSX。除了向接口添加任何类型以使其正常工作之外,我之前没有使用过打字稿。错误指向这一行

const 模板:故事 = (args) => //此处错误

您的 Button 组件接受与您声明的 ButtonProps

不同的道具

解决方案 1:在 Button 组件 decleration 中使用 Button 道具

export const Button = ({ primary, backgroundColor, size, label, onClick}:ButtonProps) => {
  const mode = primary ? 'storybook-button--primary' : 'storybook-button--secondary';
  return (
    <button
      type="button"
      className={['storybook-button', `storybook-button--${size}`, mode].join(' ')}
      style={backgroundColor && { backgroundColor }}
      onClick
    >
      {label}
    </button>
  );
};

解决方案 2:为组件使用的实际道具导出特定类型:

export interface ActualButtonProps {
  primary: boolean;
  backgroundColor: string;
  size: "small" | "medium" | "large";
  label: string;
  props: {[x:string]:any}
}

export const Button = ({ primary, backgroundColor, size, label, ...props }) => {
  const mode = primary ? 'storybook-button--primary' : 'storybook-button--secondary';
  return (
    <button
      type="button"
      className={['storybook-button', `storybook-button--${size}`, mode].join(' ')}
      style={backgroundColor && { backgroundColor }}
      {...props}
    >
      {label}
    </button>
  );
};

在你的故事书中:

const Template: Story<ActualButtonProps> = (args) => <Button {...args} />;