我正在创建一个将来会扩展的组件,因为我需要使其更加通用。
我有一个如下所示的要求。
我有一个 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 Base
和Base 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/