Suggest correct TypeScript for React wrapper function which adds 2 functions to wrapped component’s props

  javascript, reactjs, typescript

I developed function wrapping React component for adding undo/redo functionality by keyboard shortcuts Ctrl+Z/Shift+Ctrl+Z. It looks like this:

import React from 'react';

interface WithUndoRedoProps {
    addUndoRedo: (field: string, oldValue: string, newValue: string) => void;
    undoRedo: (event: KeyboardEvent) => { field: string, value: string } | null;
}

export default function withUndoRedo<P extends object>(
    WrappedComponent: React.Component<P>
): React.Component<P & WithUndoRedoProps> {
    class WithUndoRedo extends React.Component<P & WithUndoRedoProps> {
        actions: {
            field: string;
            oldValue: string;
            newValue: string;
        }[] = [];
        actionsIndex = 0;
        
        addAction = (field: string, oldValue: string, newValue: string) => {
            if (oldValue === newValue) return;
            this.actions[this.actionsIndex++] = { field, oldValue, newValue };
        }
        
        undoRedo = (event: KeyboardEvent) => {
           // Lengthy code to return { field, value } object or null
        }
        
        render() {
            return <WrappedComponent
                addUndoRedo={this.addAction}
                undoRedo={this.undoRedo}
                {...this.props as P}
            />
        }
    };
    
    return WithUndoRedo;
}

Later I decided to start using TypeScript for this project. But I don’t know how to correctly type this function. It shows TS errors and returns anonymous class.

Also I have a few other questions about typing code. Please suggest where I can find full documentation, good book titles, and any other sources documenting correct typing for React projects.

Source: Ask Javascript Questions

LEAVE A COMMENT