I've described prop children as an optional but it has default prop and even it has declared Typescript throws the error
import React, { MouseEvent } from 'react';
const defaultProps = {
children: () => null,
};
type TMouseCoordinates = { x: number, y: number };
type TProps = Partial<
{
children?: (coordinates: TMouseCoordinates) => JSX.Element | null;
} & TDefaultProps
>;
class MouseCoordinates extends React.Component<TProps, TState> {
static readonly defaultProps: TProps = defaultProps;
render() {
const { children } = this.props;
const isRenderIsFunction = typeof this.props.children === 'function';
return isRenderIsFunction ? children(this.state) : null;
^^^^^^^^
}
}
Cannot invoke an object which is possibly 'undefined'.
A dirty hack but it works: (() => null) as TRenderCallback
import React, { MouseEvent } from 'react';
const defaultProps = {
children: (() => null) as TRenderCallback,
};
type TRenderCallback = (coordinates: TMouseCoordinates) => JSX.Element | null;
type TMouseCoordinates = { x: number, y: number };
type TProps = Partial<
{
children?: TRenderCallback;
} & typeof defaultProps
>;
class MouseCoordinates extends React.Component<TProps, TState> {
static readonly defaultProps: TProps = defaultProps;
render() {
const { children } = this.props;
const isRenderIsFunction = typeof this.props.children === 'function';
return isRenderIsFunction ? children(this.state) : null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With