[英]React & TypeScript - what's the difference between `React.Component` and `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.