score:3

Accepted answer

function pick<T extends TGetReducerState, V extends ReadonlyArray<keyof T>>(object: T, keys: V):Pick<T, V[number]> {
    return keys.reduce((obj, key) => {
        if (object && Object.prototype.hasOwnProperty.call(object, key)) {
            // I made here small improvement, because I prefer to not mutate accumulator argument in reduce function
            return {
                ...obj,
                [key]: object[key]
            }
        }
        return obj;
    }, {} as Pick<T, V[number]>);
}

interface IReducerA {
    loading: boolean;
    age: number;
}

interface IReducerB {
    open: boolean
}

type TGetReducerState = IReducerA | IReducerB;

interface IState {
    reducerA: IReducerA;
    reducerB: IReducerB;
}

const state: IState = {
    reducerA: { loading: false, age: 0 },
    reducerB: { open: true },
}

const getState = <T extends keyof IState, V extends keyof IState[T]>(reducer: T, values: V[]) => pick(state[reducer], values)


const { loading, age } = getState('reducerA', ['loading', 'age'])
const { open } = getState('reducerA', ['loading', 'age']) // error



Related Query

More Query from same tag