如何在扩展 React 组件的抽象类中使用泛型?

Joe*_*ina 2 typescript reactjs

我正在创建一个扩展 React 组件的抽象类,我希望能够设置一些默认的道具,但也让扩展抽象类的组件提供自己的道具。

interface Props {                                                                       
  someProps: boolean                                                                    
}                                                                                       

abstract class AbstractPureForm<P, S> extends React.Component<Props & P, S> {
  ...
}
Run Code Online (Sandbox Code Playgroud)

如何使用:

class Other extends AbstractPureForm<{ newProps: string}, {}> { 
  ...
}
Run Code Online (Sandbox Code Playgroud)

现在这个设置给了我错误:

does not exist on type '(Props & P)["..."]'
Run Code Online (Sandbox Code Playgroud)

Jam*_*rch 5

参考:如何为组件编写抽象类(具有可扩展的状态和道具)?

编写抽象类

而不是Props & P(据我所知,无法将其指定为泛型类型参数),您的抽象类应该为其道具采用泛型值,类型为P extends Props

export interface Props {
    someProps: boolean;
}

export abstract class AbstractPureForm<P extends Props, S> extends React.Component<P, S>{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

编写具体的子类

通过扩展Props接口提供 props

您的具体子类 ,Other应该通过以下方式接受显式扩展抽象类Props接口的道具OtherProps extends Props

interface OtherProps extends Props {
    newProps: string;
}

class Other extends AbstractPureForm<OtherProps, {}> { 
    // ...
}
Run Code Online (Sandbox Code Playgroud)

通过与Props界面相交来提供道具

通过创建类型OtherConcreteProps & Props(具体子类和抽象类的 props 的交集),您可以像最初一样使用交集类型:

interface OtherConcreteProps {
    newProps: string;
}

export type OtherProps = OtherConcreteProps & Props;

class Other extends AbstractPureForm<OtherProps, {}> { 
    // ...
}
Run Code Online (Sandbox Code Playgroud)