【问题标题】:How to assign classes to properties of "new () =>" type如何将类分配给“new () =>”类型的属性
【发布时间】:2018-05-31 06:58:15
【问题描述】:

有层次

class Thing { }

class BarView<Type> extends React.Component<{ obj: Type }, {}> { }

class FlossView extends BarView<Thing> {  }

class Foo<Type> {
    renderer?: new () => BarView<Type>

    constructor(view?: new () => BarView<Type>) {
         this.renderer = view
    }
}

为什么我可以用类名签名调用Foo的构造函数而没有这样的错误

let foo = new Foo<Thing>(FlossView)

...而下面的代码会产生错误?

let foo = new Foo<Thing>()
foo.renderer = FlossView
/* [ts]
Type 'typeof FlossView' is not assignable to type 'BarView<Thing> | undefined'.
Type 'typeof FlossView' is not assignable to type 'BarView<Thing>'.*/

如何获得不是typeof FlossView 版本的课程,而只是FlossView?

【问题讨论】:

  • 实际代码与您发布的代码不同。这个按预期工作,typescriptlang.org/play/…
  • 没有view 属性,尽管错误暗示有一个。为了得到这个错误,它必须是constructor(public view?: FlossView),而不是constructor(view?: new () =&gt; BarView)。
  • @estus,阅读你的 cmets,没有明确地到达任何地方。将尝试摆弄声明...
  • @estus 哦,天哪,这个问题有一个巨大的错字!
  • 当然要对foo.renderer应用FlossView

标签: javascript reactjs typescript dependency-injection typeof


【解决方案1】:

案件已结案。签名无效,最基类React.Component 从未有过new () =&gt; React.Component 类型的构造函数。

图,构造函数只有一个参数props。 因此renderer 属性的类型声明无效。应该是

renderer?: new (props) => BarView<Type>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2020-05-22
    • 2011-12-16
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多