defaultProps in StatelessFunctionalComponent error
Getting error by setting defaultProps in stateless component:
/* @flow */
import * as React from 'react';
type TouchableProps = {borderless?: boolean, children?: React.Node};
type TouchableType = React.StatelessFunctionalComponent<TouchableProps>;
const Touchable: TouchableType = (props: TouchableProps) => <div>{props.children}</div>
Touchable.defaultProps = {borderless: false}
Expected behavior: no errors.
I just across this myself. The definition doesn't include defaultProps:
/**
* The type of a stateless functional component. In most cases these components
* are a single function. However, they may have some static properties that we
* can type check.
*/
declare type React$StatelessFunctionalComponent<Props> = {
(props: Props, context: any): React$Node,
displayName?: ?string,
propTypes?: $Subtype<{[_: $Keys<Props>]: any}>,
contextTypes?: any
};
Flow docs do not include types at all. Seems like an oversight to me.
Something that can be PRd perhaps?
If you omit TouchableType flow will infer the correct type. You also want to make the borderless field not optional, flow will infer the correct ElementConfig from Props and defaultProps.
ie:
/* @flow */
import * as React from 'react';
type TouchableProps = {borderless: boolean, children?: React.Node};
type TouchableType = React.StatelessFunctionalComponent<TouchableProps>;
const Touchable = (props: TouchableProps) => <div>{props.children}</div>
Touchable.defaultProps = {
borderless: false
};
<Touchable>no errors</Touchable>;
@pigoz: There are times when you have no other alternative than using StatelessFunctionalComponent or more generally ComponentType, for example when you want to help flow to get the type of a composition of higher-order components.
It would be super nice if we find a solution to this issue.
BTW, I forgot to mention that there is a workaround, but it's really ugly, have a look:
const defaultProps = <define your defaultProps here>;
type PropsWithDefaults = $Diff<Props, typeof defaultProps> & $Shape<typeof defaultProps>;
type YourComponent = ComponentType<PropsWithDefaults>;
// $FlowFixMe: we need this to omit the error originally described :(
Object.assign(YourComponent, {defaultProps});
I've just noticed that combining $Diff with $Shape breaks the whole type!

And AnimatedEllipsis is typed as follows:
const AnimatedEllipsis: ComponentType<
$Diff<Props, typeof defaultProps> & $Shape<typeof defaultProps>
> = ...
So the last object in the intersection should have all its props optional, and as you can see in the image they are all required, this means that $Shape has not been applied at all.
@calebmer are you aware of this issue?