繁体   English   中英

React + Typescript继承和扩展属性

[英]React + typescript inheritance and extending property

我正在创建一个将来会扩展的组件,为此我需要使其更通用。

我有一个类似下面的要求。

我有一个Base类,它接受类型为“ cell”和“ phone”的属性。

我想在NewBase类中扩展它并支持新属性newType。

我得到的错误是

[ts]由于类型'“ cell” |此条件将始终返回'false'。 “ phone”和“ 0”没有重叠。

我没有足够的想法来扩展接口来支持新课程,请帮助...

export interface IBaseType {
    type: 'cell' | 'phone' 
} 
export class Base extends React.Component<IBaseType > {
    public render() {
        const { name, type } = this.props;
        return (() => {
            switch (type) {
                case 'cell': return <h1>Cell</h1>
                case 'phone': return <h1>Phone</h1>
            }
        })()
    } 
}

interface NewType extends Omit<IBaseType, 'type'>  {
    type: 'newType' | IBaseType['type']
 }

class NewBase extends Base {
    constructor(props: NewType){}
    public render(){
       if(this.props.type === 'newType') {
          return <h1>Hi i am new type</h1>
       }
       return super.render();
    }
}

this.props的类型由传递给React.Component的props类型参数确定。 在这种情况下,其中NewBase extends BaseBase extends React.Component<IBaseType>的类型, this.props仍然是IBaseType ,这解释了错误。 如果您希望能够定义具有不同道具类型的Base子类,则需要向道具类型的Base添加一个类型参数。 这样的事情可能适合您:

interface ICommonType {
    type: string;
}
export interface IBaseType {
    type: 'cell' | 'phone' 
} 
export class Base<P extends ICommonType = IBaseType> extends React.Component<P> {
    public render() {
        const { name, type } = this.props;
        return (() => {
            switch (type) {
                case 'cell': return <h1>Cell</h1>
                case 'phone': return <h1>Phone</h1>
            }
        })()
    } 
}

interface NewType extends Omit<IBaseType, 'type'>  {
    type: 'newType' | IBaseType['type']
 }

class NewBase extends Base<NewType> {
    public render(){
       if(this.props.type === 'newType') {
          return <h1>Hi i am new type</h1>
       }
       return super.render();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM