Функция TypeScript с параметром generi c, который использует вычисляемые ключи - PullRequest
0 голосов
/ 24 апреля 2020

У меня есть две функции, которые делают одно и то же, единственное отличие - это типы. Я хочу использовать обобщенные типы c вместе с вычисляемыми свойствами, но не могу понять, какие типы / интерфейсы нужно расширять, какие. Это то, что я хочу сделать:

const getUpdatedState = <T, K>(state: T, column: K) => {
    return {...state, [column]: state[column] === 'unsorted' ? 'ascending' : 'descending'}
}

Это, очевидно, не работает, потому что T может иметь различные свойства. Есть ли способ сделать это с обобщенными c типами?

Вот типы и фактический код:

Типы:

export type DMessageKeys =
    | 'conversationId'
    | 'created'
    | 'lastUpdate'
    | 'serviceIdentifier'
    | 'senderIdentifier'
    | 'receiverIdentifier'
    | 'latestMessageStatus'

export type DSortingState = {
    [key in DMessageKeys]: Sorts
}

export type EMessageKeys =
    | 'conversationId'
    | 'externalId'
    | 'lastUpdated'
    | 'createdDate'
    | 'sendingStatus'

export type ESortingState = {
    [key in EMessageKeys]: Sorts
}

export type Sorts = 'unsorted' | 'ascending' | 'descending'

и функции:

export const getUpdatedDSortingState = (
    initialState: DSortingState,
    currentState: DSortingState,
    column: DMessageKeys
): DSortingState => {
    return {
        ...initialState,
        [column]:
            currentState[column] === 'unsorted' || currentState[column] === 'descending'
                ? 'ascending'
                : 'descending',
    }
}

export const getUpdatedESortingState = (
    initialState: ESortingState,
    currentState: EsortingState,
    column: EMessageKeys
): ESortingState => {
    return {
        ...initialState,
        [column]:
            currentState[column] === 'unsorted' || currentState[column] === 'descending'
                ? 'ascending'
                : 'descending',
    }
}

1 Ответ

0 голосов
/ 24 апреля 2020

Если я правильно понимаю, вы должны это сделать.

const getUpdatedState = <T, K>(state: T, column: K) : any => { // you can also set the real types with "typeX | typeY"
    return {...state, [column]: state[column] === 'unsorted' ? 'ascending' : 'descending'}
}

const updatedState = getUpdateState<type1, type2>(state, column);
...