给定一个像这样的状态 reducer :
const anObject = {
fruit: 'Apple',
today: new Date(),
}
function reducer(state, stateReducer) {
return stateReducer(state);
}
const fruit = reducer(anObject, state => state.fruit);
// fruit should be of type string.
const now = reducer(anObject, state => state.now);
// now should be of type Date.
我想使用 Typescript 泛型,以便从 reducer(anObject, state => state.someState)
返回的状态根据它返回的开始部分是正确的类型。我怎样才能做到这一点?谢谢
这是上述的一个可运行示例:https://codesandbox.io/s/adoring-booth-jlnhn
最佳答案
看起来reducer
函数的返回类型应该与传递的stateGetter
函数的返回类型相同。此外,stateGetter
应该接受作为其参数传递给 reducer
的第一个参数的相同类型。
因此,如果 S
是状态的类型,而 R
是 stateGetter
的返回类型,那么您可以编写如下函数所以:
function reducer<S, R>(state: S, stateGetter: (state: S) => R): R { /* ... */ }
然后你想要的推论就会发生:
const fruit = reducer(anObject, state => state.fruit); // Has type: string
const today = reducer(anObject, state => state.today); // Has type: Date
关于javascript - 减少时如何使用 TS 泛型从状态中提取正确的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60332320/