如何重用常见类型

时间:2019-07-29 18:21:44

标签: javascript reactjs typescript

我有多个可重复使用相同道具的react组件,并且想知道我是否有一种简单的方法来存储和重复使用这些类型。

例如:

之前

import * as React from 'react';

interface AnotherButtonProps {
  disabled?: boolean;
  onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
}

interface SampleButtonProps {
  disabled?: boolean;
  onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
  title: string;
}

const AnotherButton: React.FC<AnotherButtonProps> = ({ disabled = false, onClick }) => (
  <button
    disabled={disabled}
    onClick={onClick}
    type="button"
  >
    This is another button
  </button>
);

const SampleButton: React.FC<SampleButtonProps> = ({ disabled = false, onClick, title }) => (
  <button
    disabled={disabled}
    onClick={onClick}
    type="button"
  >
    {title}
  </button>
);

之后:

import * as React from 'react';

interface Disabled {
  disabled?: boolean;
}

interface OnClick {
  onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
}

interface Title {
  title: string;
}

interface AnotherButtonProps {
  disabled?: Disabled;
  onClick: OnClick;
}

interface SampleButtonProps {
  disabled?: Disabled;
  onClick: OnClick;
  title: Title;
}

const AnotherButton: React.FC<AnotherButtonProps> = ({ disabled = false, onClick }) => (
  <button
    disabled={disabled} // get error
    onClick={onClick}
    type="button"
  >
    This is another button
  </button>
);

const SampleButton: React.FC<SampleButtonProps> = ({ disabled = false, onClick, title }) => (
  <button
    disabled={disabled}
    onClick={onClick}
    type="button"
  >
    {title}
  </button>
);

当我尝试重用这些通用接口时,出现以下错误:

  

TS2322:输入“布尔值|禁用”不是可分配的类型“布尔值”。不能将“已禁用”类型分配给“布尔”类型。

1 个答案:

答案 0 :(得分:2)

您需要使用工具

例如:

interface SampleButtonProps implements Disabled, OnClick, Title {}