我在运行此代码时遇到一个非常奇怪的错误(React+Typescript):
// doesn't work
<TestClass
input={InputFunction}
/>
还有这个代码:
// doesen't work
<TestClass
input={(props:TestProps) => InputFunction}
/>
它们都将返回错误“没有与此调用匹配的重载”。奇怪的是,由于在 defaultProps
中提供了 TestClass
(其中提供了 InputFunction
),下面的代码会起作用。
// works!
<TestClass/>
我的源代码如下。您可以通过使用以下代码创建两个文件(InputFunction.ts
和 TestClass.tsx
)来复制它,然后尝试在同一项目的单独文件中运行上述代码(以及导入语句和通常的样板).
// InputFunction.ts
export const InputFunction = <T>(
props: { widthRatio: number },
): number => {
return 0
};
// TestClass.tsx
import * as React from "react";
import { InputFunction } from "./InputFunction"
export interface TestProps {
readonly input?: ((props: TestProps) => number);
}
export class TestClass extends React.Component<TestProps> {
public static defaultProps = {
input: InputFunction,
};
public render() {
return (
null
);
}
}
答案 0 :(得分:1)
在您的接口 TestProps 中,您用问号声明 input?
。这使它成为可选的,并解释了为什么没有任何道具的示例有效。
我认为主要错误来自你对 props 接口的定义:
export interface TestProps {
readonly input?: ((props: TestProps) => number);
}
这是递归的。您不需要 TestProps
类型的参数。相反,该参数应与您的函数 props: { widthRatio: number }
一旦签名匹配,我希望编译器接受 InputFunction
。