简体   繁体   中英

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

If I have the following component

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 />;
    }
}

Then this.props.someOptionalProp has type string | undefined string | undefined , since this is an optional field of the Props interface. However, at runtime it cannot be undefined since defaultProps are set for this prop.

Is there any way to avoid typecasting in this situation?

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

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

TypeScript is trying to warn you that probably this props will have no value. Anyways, if you want to be specific in the type used, you can use Type Assertion.

Note that type assertions are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed.

You could read more here: https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html

In your case the solution could be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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