【问题标题】:how can i accept react component constructor as a function param in typescript我如何接受反应组件构造函数作为打字稿中的函数参数
【发布时间】:2017-12-06 02:13:10
【问题描述】:
import { Component} from "react";

export class Test extends Component<{}, {}> {
      render() {
        return "Hello";
      }
    }

    function myFunction<P, S, C extends Component<P, S>>(c: C): void {
      console.log("ctor", c);
    }

    const s = myFunction(Test);

错误:

“typeof Test”类型的参数不能分配给类型参数 '组件'。类型“typeof”中缺少属性“setState” 测试'。 07:35:53 - 编译完成。监视文件更改。

我是否需要使用 super.(..) 实现原始 react Component 类的所有成员?

【问题讨论】:

    标签: typescript typescript2.0


    【解决方案1】:

    您需要将C 的类型声明为扩展返回组件的新函数:

    import { Component} from "react";
    
    export class Test extends Component<{}, {}> {
        render() {
            return "Hello";
        }
    }
    
    function myFunction<P, S, C extends new () => Component<P, S>>(c: C): void {
        console.log("ctor", c);
    }
    
    const s = myFunction(Test);
    

    【讨论】:

    • 仍然出现错误!,错误 TS2345:“typeof Test”类型的参数不可分配给“new () => Component”类型的参数。
    • @invariant 这很有趣。当我编译它时,相同的 sn-p 不会给我任何错误。事实上,我什至可以毫无问题地写var x: new () =&gt; Component = Test。不知道为什么我们的结果之间存在差异。你的打字稿版本是什么?
    • > tsc -v = 版本 2.6.2
    • 嗯。更新我的相同,仍然没有问题。这是您在 IDE 中还是在实际的 tsc 命令输出中看到的错误?
    • @invariant 等一下,我刚刚有了一个想法。您的示例类没有构造函数,因此 newable 函数不带参数。但是你的实际实现有构造函数参数吗?如果是这样,您可以尝试使用new (...args: any[]) =&gt; Component&lt;P, S&gt;。编辑:或者为了更多的类型安全new (props: P, state: S) =&gt; Component&lt;P, S&gt;
    猜你喜欢
    • 1970-01-01
    • 2019-08-16
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 2020-07-17
    • 1970-01-01
    • 2021-08-03
    相关资源
    最近更新 更多