【问题标题】:"Cannot invoke an expression whose type lacks a call signature" in Typescript?Typescript中的“无法调用类型缺少调用签名的表达式”?
【发布时间】:2019-09-28 07:18:29
【问题描述】:

我有一个 React-Final-Form,我想用它自己的类型输入它。 但是 `children(renderRest)' 给出了以下错误:

无法调用类型缺少调用签名的表达式。类型 '字符串 |号码 |真实 | {} |反应元素反应元素 组件)> |空) | (新(道具:任何)=> 组件)> |反应节点数组 |反应门户 | ((道具: FormRenderProps) => ReactNode)' 没有兼容的调用 签名.ts(2349)

我的代码是:

import React from "react";
import styled from "styled-components";
import { Form as StateForm, FormProps } from "react-final-form";

import Box from "src/App/Components/Layout/Box";

const StyledForm = styled(Box)``;

const Form = ({ children, ...rest }: FormProps) => {
  return (
    <StateForm
      {...rest}
      render={({ handleSubmit, ...renderRest }) => (
        <StyledForm as="form" onSubmit={handleSubmit}>
          {children && children(renderRest)}
        </StyledForm>
      )}
    />
  );
};

export default React.memo(Form);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

此错误“无法调用类型缺少调用签名的表达式”在我能够解决的各种情况下发生。但不幸的是,这不是这个案子。

请问有什么提示吗?谢谢

【问题讨论】:

    标签: typescript typescript-typings react-final-form final-form


    【解决方案1】:

    react-final-form 的类型定义中,它将RenderablePropsFormProps 扩展)中的children 定义为:

    export interface RenderableProps<T> {
      children?: ((props: T) => React.ReactNode) | React.ReactNode;
      component?: React.ComponentType<T> | string;
      render?: (props: T) => React.ReactNode;
    }
    

    所以children 要么是一个接收props 并创建React.ReactNode 的函数,要么它是一个直接的React.ReactNode 实例。在后一种情况下,您不能像函数一样使用它。因为它可能是任何一个 TS 只会让你做两者之间共同的事情。错误Cannot invoke an expression whose type lacks a call signature. 基本上是在说:“你试图像使用函数一样使用children,这是不允许的,因为我不确定它是否是函数。”

    我不太了解react-final-form 库,无法说出解决此问题的最佳方法。你可以投...

    (children as ((props: T) => React.ReactNode))(renderRest);
    

    ...或者您可以添加类型保护...

    if (typeof children === 'function') {
      children(renderRest);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-01
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      • 2018-12-25
      • 1970-01-01
      • 2015-08-26
      相关资源
      最近更新 更多