reactjs - React 中的 typescript : Props type check is not working

标签 reactjs typescript typescript2.0 react-proptypes

我在我的 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/

相关文章:

reactjs - NextJS : how to Link to new page with current page slugs?

reactjs - 使用 react-router-dom 停止页面中侧边栏的重新渲染

angular - 在 Angular 中,*ngFor ="let item from list | async"是什么意思?

typescript - 如何获取和设置 div.class 高度

javascript - 如何为导出多个函数的模块编写中间件逻辑

reactjs - 类组件内的导航不起作用

javascript - 无法映射可迭代的 Prop 对象

javascript - d3.js v5.9.1 - 此版本中的某些方法未按预期工作

angular2自定义表单输入无法读取未定义的属性 'name'

javascript - 重命名对象/接口(interface)类型安全的键