【发布时间】:2019-12-27 22:38:01
【问题描述】:
我用一些道具创建了一个简单的类组件。从 Typescript 3 及更高版本开始,他们声明 defaultProps 默认将使用与组件的 props 本身相同的接口。 reference
在下面的代码示例中,您可以看到我创建了一个组件,使用给定接口扩展了 React.PureComponent。一个 prop 称为 boolean,类型为 boolean。
然后我得到了static defaultProps 分配,我在其中输入了一个字符串而不是布尔值。
import React from "react";
export interface ExampleClassProps {
string: string;
arrayOfStrings: { test: string };
boolean: boolean;
}
class ExampleClass extends React.PureComponent<ExampleClassProps> {
static defaultProps = {
string: "asd",
arrayOfStrings: { test: "asd" },
boolean: "true" //this should throw an error, since I'm assigning a string to type boolean
};
render() {
return <div>{this.props.string}</div>;
}
}
export default ExampleClass;
根据我的理解,Typescript 现在应该抛出一个错误,说 type string is not assignable to type boolean,但事实并非如此。
我使用的是 Typescript 3.5.3,我安装了 @types/react。
另外,编写一个类似的组件作为功能组件确实有效,所以我只遇到了类的问题:
import React from "react";
export interface ExampleFCProps {
stringProp?: string;
}
const ExampleFC: React.FC<ExampleFCProps> = ({ stringProp }) => {
return <div>{stringProp}</div>;
};
ExampleFC.defaultProps = { stringProp: 1 }; //this throws an error, since number is not type string
export default ExampleFC;
【问题讨论】:
标签: reactjs typescript class components