I\'m using React with TypeScript and I\'ve created stateless function. I\'ve removed useless code from the example for readability.
interface CenterBoxProps exte
Typing default props in function component with React.FC can result in false type error:
type Props = {
required: string,
} & typeof defaultProps;
const defaultProps = {
optDefault: 'optDefault'
};
const MyComponent: React.FC = (props: Props) => (
- required: {props.required}
- optDefault: {props.optDefault}
)
MyComponent.defaultProps = defaultProps;
ReactDOM.render(
,
document.getElementById('app')
);
error:
[tsserver 2741] Property 'optDefault' is missing in type '{ required: string; }' but required in type '{ optDefault: string; }'. [E]
Another solution proposed is to use Javascript's own default function parameters:
type Props = {
required: string,
optDefault?: string
}
const MyComponent: React.FC = ({
required,
optDefault='default'
}: Props) => (
- required: {required}
- optDefault: {optDefault}
)
ReactDOM.render(
,
document.getElementById('app')
);
But the problem with this solution is that if you forgot to provide default, a run time bug will result:
const MyComponent: React.FC = ({
required,
optDefault //='optDefault' //<--- if you forgot to provide default
}: Props) => (
- required: {required}
- optDefault: {optDefault}
{/* <-- result in bug */}
)
A better solution is not using React.FC at all, simply rely on Typescript type inference:
type Props = {
required: string,
} & typeof defaultProps;
const defaultProps = {
optDefault: 'optDefault'
};
const MyComponent = (props: Props) => (
- required: {props.required}
- optDefault: {props.optDefault}
)
MyComponent.defaultProps = defaultProps
ReactDOM.render(
,
document.getElementById('app')
);