I'm unable to determine how to specify a non-optional component property that is provided via defaultProps if not specified during construction from typescript.
My source:
'use strict';
import * as React from 'react';
import {DOM as dom} from 'react';
import * as ReactDOM from 'react-dom';
interface PropsType {
requiredString: string,
optionalString?: string,
};
class MyComponent extends React.Component<PropsType, {}> {
static defaultProps = {
requiredString: 'defaultRequiredString',
};
render() {
return dom.div(
{},
this.props.requiredString,
this.props.optionalString || 'defaultOptionalString',
);
}
}
ReactDOM.render(React.createElement(MyComponent, {}));
This gives me:
$ tsc base.ts
base.ts(25,50): error TS2345: Argument of type '{}' is not assignable
to parameter of type 'Attributes & PropsType'.
Type '{}' is not assignable to type 'PropsType'.
Property 'requiredString' is missing in type '{}'.
Reading through the React docs (https://facebook.github.io/react/docs/typechecking-with-proptypes.html), I see the following:
The propTypes typechecking happens after defaultProps are resolved, so typechecking will also apply to the defaultProps.
Which leads me to believe this form should be allowed (and indeed, the large codebase I'm trying to port to typescript has this assumption baked in). I'd be happy to use a Partial<>
type for defaultProps
if that in any way helps.
How do get this working properly in typescript?