Cameron Martin
Cameron Martin

Reputation: 6010

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, 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?

Upvotes: 3

Views: 568

Answers (2)

Jos&#233; Quinto Zamora
Jos&#233; Quinto Zamora

Reputation: 2128

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'); 

Upvotes: 1

Amid
Amid

Reputation: 22382

I think you can use non-null assertion operator for this purpose:

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

Upvotes: 2

Related Questions