Say you define your component like so:
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 the defaulted prop from you, even though it's defined in defaultProps:
<Comp req="something" /> // ERROR: TypeScript: prop 'defaulted' is required
However, if you define the props interface like so:
interface IProps {
req: string;
defaulted?: string; // note the ? here
}
then you cannot use it in:
render() {
const { defaulted } = this.props; // ERROR: prop 'defaulted' possibly undefined
return (
<span>{defaulted.toUpperCase()}</span>
);
}
How to define the IProps, defaultProps and component correctly so the types make sense?
EDIT:
I'm using the strictNullChecks flag.
static defaultProps: IDefaultProps = { validate: () => null, defaultValue: '', };