简体   繁体   中英

TypeScript function with generic parameter which uses computed keys

I have two functions which do the same thing, the only difference is the types. I want to use generic types together with computed properties, but can't wrap my head around which types/interfaces need to extend which. This is what I want to do:

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

This obviously does not work, because T can have different properties. Is there a way of doing this with generic types?

Here's the types and the actual code:

Types:

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'

and the functions:

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

If i understand you correct this should do it.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM