У меня есть две функции, которые делают одно и то же, единственное отличие - это типы. Я хочу использовать обобщенные типы 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',
}
}