Johannes Klauß
Johannes Klauß

Reputation: 11020

Typescript: Extend prop interface of custom parent React.Component

I have a abstract Row class in my Typescript/React app:

export interface IAbstractRowProps {
    assignedValueY: IValue;
    valueZId?: number;
    matrixStore?: MatrixStore;
}
export abstract class AbstractRow extends React.Component<IAbstractRowProps, {}> {
    // ...

A conrecte component inherits from that:

export default class DayRow extends AbstractRow {
    protected getCellItems(): ICellItem[] {
        // ...
    }
}

And then I want a second component to inherit from DayRow. But I also want to extend the props on this component. Something like this:

export interface IDayFinderRowProps extends IAbstractRowProps {
    anotherProp: boolean;
}

export default class DayFinderRow<IDayFinderRowProps, {}> extends DayRow {
    protected getCellItems(): ICellItem[] {
        // ...
    }
}

This syntax produces errors. I this even possible to achieve or do I have to add all the props I might need to the IAbstractRowProps interface?

Upvotes: 1

Views: 2314

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249676

You need to make DayRow and AbstractRow generic themselves so the generic type can flow to React.Component. For DayRow you can specify the default type, so you can instantiate it without specifying the generic parameter.

export abstract class AbstractRow<T extends IAbstractRowProps> extends React.Component<T, {}> {
}

export class DayRow<T extends IAbstractRowProps = IAbstractRowProps> extends AbstractRow<T> {

}
export class DayFinderRow extends DayRow<IDayFinderRowProps> {

}

Upvotes: 2

Related Questions