3
votes

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'.

2

2 Answers

2
votes

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;
    }
}