React Native Typescript:类型'string'不能分配给类型'“ solid” | “清除” | “ outline”'。ts(2322)

时间:2019-04-19 14:33:09

标签: reactjs typescript react-native

我正在将TypeScript与React Native一起使用。

import React from 'react';
import { Button } from 'react-native-elements';
import { IThemedButton } from '../../../models/themedButton';

interface IThemedButtonProps {
  data: IThemedButton;
}

const ThemedButton: React.FC<IThemedButtonProps> = ({
  data: { title, type, onPress },
}) => {
  return <Button title={title} type={type} onPress={onPress} />;
};

export default ThemedButton;

export interface IThemedButton {
  title: string;
  type: string;
  onPress: any;
}

我将类型设置为字符串,因为按钮标题是字符串,但是VS Code向我显示错误:

Type 'string' is not assignable to type '"solid" | "clear" | "outline"'.ts(2322)
index.d.ts(326, 3): The expected type comes from property 'type' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<ButtonProps> & Readonly<{ children?: ReactNode; }>'

我在文档中读到,该类型是可选的: https://react-native-training.github.io/react-native-elements/docs/button.html#type

有什么解决方案?

2 个答案:

答案 0 :(得分:2)

type只能是“ solid”,“ clear”或“ outline”这三样,因此TypeScript希望将其定义为类型。即使它们是字符串,出于某种原因,TypeScript仍希望将它们定义为“实心”,“清晰”或“轮廓”。

export interface IThemedButton {
  title: string;
  type: 'solid' | 'clear' | 'outline';
  onPress: any;
}

答案 1 :(得分:0)

这里的类型是具有[[solid],“ clear”,“ outline”]值的枚举

尝试添加其中任何一个,并且预期的类型来自属性“ type”

因此代码将

export interface IThemedButton {
  title: string;
  type: type;
  onPress: any;
}