Typescript中的“无法调用类型缺少呼叫签名的表达式”?

时间:2019-05-10 11:19:04

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

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

  

无法调用类型缺少调用签名的表达式。类型   '字符串|编号真实| {} | ReactElement ReactElement   组件)> | null)| (新(道具:任意)=>   组件)> | ReactNodeArray | ReactPortal | ((道具:   FormRenderProps)=> ReactNode)'没有兼容的调用   signatures.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>

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

请问有什么提示吗?谢谢

1 个答案:

答案 0 :(得分:0)

react-final-form的类型定义中,它在childrenRenderableProps进行了扩展)中将FormProps定义为:

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,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);
}
相关问题