Say that you define your component as follows:
interface IProps {
req: string;
defaulted: string;
}
class Comp extends React.Component<IProps, void> {
static defaultProps = {
defaulted: 'test',
};
render() {
const { defaulted } = this.props;
return (
<span>{defaulted.toUpperCase()}</span>
);
}
}
when you want to use it, TypeScript wants defaultedprop from you , although it is defined in defaultProps:
<Comp req="something" /> // ERROR: TypeScript: prop 'defaulted' is required
However, if you define the props interface as follows:
interface IProps {
req: string;
defaulted?: string;
}
then you cannot use it in:
render() {
const { defaulted } = this.props;
return (
<span>{defaulted.toUpperCase()}</span>
);
}
How to define IProps, defaultProps and component correctly so that types make sense?
EDIT:
I use the flag strictNullChecks.
source
share