[英]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.这显然是行不通的,因为
T
可以有不同的属性。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.