Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Cannot invoke an object which is possibly 'undefined'. for default prop is defined

Tags:

typescript

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

like image 937
Vadim Avatar asked May 09 '26 20:05

Vadim


1 Answers

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;
    }
}
like image 128
Vadim Avatar answered May 11 '26 11:05

Vadim