简体   繁体   中英

How to use TS generics to extract correct type from state when reducing

Given a state reducer like this:

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.

I would like use Typescript generics so that the returned state from reducer(anObject, state => state.someState) is the correct type according to the part of the start it returns. How can I achieve that? Thanks

Here's a runnable example of the above: https://codesandbox.io/s/adoring-booth-jlnhn

Seems like the return type of the reducer function should be just the same as the return type of the passed stateGetter function. Additionally, stateGetter should accept as its arugment the same type passed as the first argument to reducer .

So if S is the type of the state, and R is the return type of stateGetter , then you could write the function like so:

function reducer<S, R>(state: S, stateGetter: (state: S) => R): R { /* ... */ }

Then the inferences you want happen:

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.

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