错误:无法调用可能是“未定义”的对象。为默认道具定义

时间:2018-07-01 19:00:34

标签: typescript

我已经将prop children描述为可选,但它具有默认prop,甚至声明Typescript都会引发错误

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

无法调用可能是“未定义”的对象。

2 个答案:

答案 0 :(得分:2)

肮脏的骇客,但可以使用:(() => 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;
    }
}

答案 1 :(得分:0)