我在我的 React 应用程序中使用 Typescript。我想严格检查传递给组件的 props 类型,如果不匹配则抛出错误。
import React from "react";
import styles from "./ServiceDetailCard.css";
type Service = {
amount: string;
comments: string;
};
interface IProps {
service: Service;
myFunc: (count: number) => void; // The function passed from parent has different return type(boolean) and defaul param as string type. But typescript doesnt throw error.
}
class ServiceDetailCard extends React.Component<IProps, any> {
render() {
console.log(typeof this.props.service.amount); // This prints number. Typscirpt should have thrown an error since interface specified is string. But it doesnt.
return (
<div className={styles.serviceDetailCard}>
<div className={styles.amount}>
<span className={styles.figure}>{this.props.service.amount}</span>
</div>
</div>
);
}
}
export default ServiceDetailCard;
import React from "react";
import styles from "./ServiceDetails.css";
import ServiceDetailsCard from "./ServiceDetailCard";
class ServiceDetails extends React.Component {
render() {
return (
<div className={styles["service-details"]}>
{this.props.data.map((service, index) => {
service.amount = 10; // To test, manually setting amount as number so that Typescript should throw error. But it doesnt.
return <ServiceDetailsCard key={index} service={service} myFunc={test} />;
})}
</div>
);
}
}
function test(number = 10) { // To test, manually setting the default param as string so that Typescript should throw error. But it doesnt.
return true; // To test, manually setting return as boolean so that Typescript should throw error. But it doesnt.
}
export default ServiceDetails;
服务属性预计包含数字形式的金额(通过接口(interface)指定),但即使我从父组件传递字符串,它也能工作并且 typescript 不会抛出错误。
与函数 prop myFunc 相同,它需要数字参数且返回类型为 void。但我传递了不同类型的默认参数,并且返回类型是 bool 值。
为什么 typescript 不抛出错误?
这是我的 .tsconfig:
{
"compilerOptions": {
"outDir": "./www/",
"sourceMap": true,
"noImplicitAny": true,
"strict": true,
"strictNullChecks": true,
"module": "es6", // specify module code generation
"moduleResolution": "node",
"jsx": "react", // use typescript to transpile jsx to js
"target": "es5", // specify ECMAScript target version
"allowJs": true, // allow a partial TypeScript and JavaScript codebase
"allowSyntheticDefaultImports": true
},
"include": ["./src/**/*"]
}
请指教。
最佳答案
您的 ServiceDetails
未指定 props 类型,因此 this.props.data
的值为 any
。 TypeScript 不会从任何设置值推断类型。
let services: any;
services.ammount = 42;
// services is still any, and services.ammount also is any.
要解决此问题,请显式声明 ServiceDetails 属性。
interface Service {
ammount: number;
}
interface ServiceDetailsProps {
services: Service[];
}
class ServiceDetails extends React.Component<ServiceDetailsProps, {}> {
...
关于reactjs - React 中的 typescript : Props type check is not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49291557/