javascript - 减少时如何使用 TS 泛型从状态中提取正确的类型

标签 javascript typescript

给定一个像这样的状态 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 是状态的类型,而 RstateGetter 的返回类型,那么您可以编写如下函数所以:

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

Here's your codesandbox with that modification.

关于javascript - 减少时如何使用 TS 泛型从状态中提取正确的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60332320/

相关文章:

javascript - 仅使用 javascript 查找 sibling 并添加类

javascript - 是否有允许字符串在 JS 中发生变异的解决方法?或者将复杂的 CSS 声明为 NOT 字符串?

javascript - 选择列表禁用出错

Javascript 对象属性名称

javascript - 我似乎无法更新 javascript/typescript 中数组中对象字段的值?

javascript - Typescript - 如何将字符串 ("console.log") 转换为函数 (console.log)

javascript - 拖放 firefox ghost 图像位置

javascript - 如何在 jQuery 中执行 if 语句?

typescript - 类型 'noUiSlider' 上不存在属性 'HTMLElement'

typescript - "Inject"带有异步/等待的回调