具有通用参数的TypeScript函数,它使用计算键

我有两个执行相同功能的函数,唯一的区别是类型。我想将泛型类型与计算属性一起使用,但是无法围绕需要扩展哪些类型/接口的问题。这就是我想做的:

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

我该如何使用泛型类型?

这是类型和实际代码:

类型:

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',
    }
}

评论