【问题标题】:With React + TypeScript, how do I avoid typecasting when using optional props with defaults with strictNullChecks enabled?使用 React + TypeScript,当使用具有默认值且启用了 strictNullChecks 的可选道具时,如何避免类型转换?
【发布时间】:2017-05-10 11:50:26
【问题描述】:

如果我有以下组件

interface Props {
    someOptionalProp?: string;
}


class SomeComponent extends React.Component<Props, {}> {
    public static defaultProps = {
        someOptionalProp: 'some default'
    };

    public render() {
        this.props.someOptionalProp.indexOf('a'); // Type error

        return <div />;
    }
}

那么this.props.someOptionalProp 的类型为string | undefined,因为这是Props 接口的可选字段。但是,在运行时它不能被 undefined,因为 defaultProps 是为这个 prop 设置的。

在这种情况下有什么方法可以避免类型转换?

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    我认为您可以为此目的使用non-null assertion operator

    this.props.someOptionalProp!.indexOf('a')
    

    【讨论】:

      【解决方案2】:

      TypeScript 试图警告你,这个 props 可能没有任何价值。 无论如何,如果你想明确使用的类型,你可以使用 Type Assertion。

      请注意,类型断言纯粹是一种编译时间构造,是一种向编译器提供有关如何分析代码的提示的方法。 p>

      您可以在这里阅读更多内容:https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html

      在您的情况下,解决方案可能是:

      (this.props.someOptionalProp as string).indexOf('a'); 
      

      【讨论】:

        猜你喜欢
        • 2020-08-03
        • 1970-01-01
        • 2019-03-19
        • 1970-01-01
        • 2022-11-23
        • 2019-12-27
        • 2017-03-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多