簡體   English   中英

Typescript typeof React.Component的子類

[英]typescript typeof subclass of React.Component

我有一個擴展React.Component的基類,並由幾個子類擴展。 現在,我希望將Parent類的類型作為屬性的類型,並且所有Child類都應對該屬性有效。 我試過這個答案 ,但是當Parent擴展React.Component時它不起作用。

class Parent extends React.Component{}
class Child1 extends Parent {}
class Child2 extends Parent {}
type F = {
  cp: { new(): Parent }
}
let f: F = {
  cp: Child1 //type 'typeof Child' is not assignable to type 'new () => Parent'.
}

您的構造函數簽名要求該類型具有一個空的構造函數,但是從React.Component繼承的構造React.Component具有兩個參數。 這就是為什么typeof Child無法分配給new ()=> Parent 您需要指定構造函數采用以下參數:

class Parent extends React.Component { }
class Child1 extends Parent { }
type F = {
    cp: { new(props: any, context?: any): Parent }
}
let f: F = {
    cp: Child1 //ok
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM