繁体   English   中英

使用React + TypeScript,当使用启用了strictNullChecks的默认值的可选道具时,如何避免类型转换?

[英]With React + TypeScript, how do I avoid typecasting when using optional props with defaults with strictNullChecks enabled?

如果我有以下内容

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 string | undefined ,因为这是Props接口的可选字段。 但是,在运行时它不能是不确定的,因为为此道具设置了defaultProps。

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

我认为您可以为此目的使用非null断言运算符

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

TypeScript试图警告您,该道具可能毫无价值。 无论如何,如果要具体说明所使用的类型,则可以使用“类型声明”。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM