在props界面中访问React类型

时间:2019-05-30 10:47:57

标签: javascript reactjs typescript

我有一个类似的功能组件:

import React, { memo } from 'react';

import {
  ButtonStyled,
  LinkStyled,
  Text,
} from './index.style';


export interface Props {
  buttonType?: string;
  handleClick?: () => void;
  href?: string;
  invertColors?: boolean;
  isDisabled?: boolean;
  isLoading?: boolean;
  text: string;
  variant?: 'dark' | 'light';
}

const defaultProps = {
  buttonType: 'button',
  handleClick: null,
  href: null,
  invertColors: false,
  isDisabled: false,
  isLoading: false,
  variant: 'dark',
};


const Button = ({
  buttonType,
  handleClick,
  href,
  isDisabled,
  isLoading,
  text,
  variant,
}: Props) => {
  if (href) {
    return (
      <LinkStyled
        href={href}
        isDisabled={isDisabled}
        isLoading={isLoading}
        variant={variant}
      >
        <Text isLoading={isLoading}>
          {text}
        </Text>
      </LinkStyled>
    );
  }

  return (
    <ButtonStyled
      disabled={isDisabled}
      isDisabled={isDisabled}
      isLoading={isLoading}
      onClick={handleClick}
      type={buttonType}
      variant={variant}
    >
      <Text isLoading={isLoading}>
        {text}
      </Text>
    </ButtonStyled>
  );
};


Button.defaultProps = defaultProps;

export default memo(Button);

此文件中只有一个Typescript错误,与type={buttonType}行有关。错误是:

Type 'string | undefined' is not assignable to type '"button" | "reset" | "submit" | undefined'.

我了解此错误。 React类型已经声明“类型”属性必须为“按钮”,“重置”,“提交”或“未定义”,但是我将道具设置为字符串或未定义。

我的问题是,如何通过手动输入所有选项将React中的选项分配给我的道具以避免重复?

编辑:此处出现完整错误:

Type 'string | undefined' is not assignable to type '"button" | "reset" | "submit" | undefined'.
  Type 'string' is not assignable to type '"button" | "reset" | "submit" | undefined'.ts(2322)
index.d.ts(1849, 9): The expected type comes from property 'type' which is declared here on type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | "style" | "title" | "className" | "color" | ... 259 more ... | "value"> & { ...; } & ButtonStyledProps, "isDisabled" | ... 267 more ... | "value"> & Partial<...>, "isDisabled" | ... 267 more ....'

@ types / react中有问题的类型如下:

interface ButtonHTMLAttributes<T> extends HTMLAttributes<T> {
  autoFocus?: boolean;
  disabled?: boolean;
  form?: string;
  formAction?: string;
  formEncType?: string;
  formMethod?: string;
  formNoValidate?: boolean;
  formTarget?: string;
  name?: string;
  type?: 'submit' | 'reset' | 'button';
  value?: string | string[] | number;
}

1 个答案:

答案 0 :(得分:3)

您可以使用类型查询来访问type的类型:

type ButtonType = JSX.IntrinsicElements['button']['type']

使用此类型(或直接使用类型查询)作为buttonType的类型可以解决您的问题:

export interface Props {
  buttonType?: ButtonType; // or directly JSX.IntrinsicElements['button']['type']
  handleClick?: () => void;
  href?: string;
  invertColors?: boolean;
  isDisabled?: boolean;
  isLoading?: boolean;
  text: string;
  variant?: 'dark' | 'light';
}