javascript - React + Typescript 继承和扩展属性

标签 javascript reactjs typescript

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

我有一个如下所示的要求。

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

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

我收到的错误是

[ts] This condition will always return 'false' since the types '"cell" | "phone"' and '0' have no overlap.

我没有得到足够的想法来扩展接口(interface)以支持新类 请帮忙...

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 的子类具有不同的 props 类型,您需要将类型参数添加到 Base对于 Prop 类型。像这样的东西可能适合你:

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();
    }
}

关于javascript - React + Typescript 继承和扩展属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53063362/

相关文章:

javascript - Material UI/Webpack/React - 生产模式下的类名优化/缩小

reactjs - reducer 的测试返回不等于预期的结果

typescript - NestJS 中的 CouchDB

javascript - 本地存储 : Storing data individually VS one big String?

typescript - ts-node-dev 不应用自动重新加载的更改

javascript - 尝试添加和删除类时,$ 未在 ejs 文件中定义

javascript - JavaScript 对 Number(undefined) 做了什么?

javascript - 如何检测浏览器是否可以在 iframe 中打开网络文件夹?

javascript - 应用 appendTo 将排序节点添加到应用模板

reactjs - 将状态传递给 sibling onChange