Artjom Vassiljev
Artjom Vassiljev

Reputation: 3

Issue with createSelector types after upgrading redux-toolkit

After upgrading redux-toolkit from 1.5 to 1.8, none of my custom selectors are valid anymore. Here is an example of one:

const getToken = createSelector<
  AppState,
  string | null,
  Token | null
>(
  (s: AppState) => (s.tokenResponse ? s.tokenResponse.accessToken : null),
  (t: string | null) => {
    if (t === null) {
      return null;
    }
    try {
      return JwtDecode(t);
    } catch (e) {
      return null;
    }
  }
);

After the upgrade my IDE complains that instead of 2 type arguments I am passing 3. However I couldn't find anywhere in the docs that now it accepts only 2 type arguments.

Removing string | null (or any of the other arguments) didn't help either, and only thing that helped was to leave createSelector<any, any>(...).

How can I figure out which type definition createSelector is expecting? And where can I find docs where it is described which two types are expected?

Upvotes: 0

Views: 872

Answers (1)

phry
phry

Reputation: 44086

The types are inferred - you should not declare that generic by hand.

Just write

const getToken = createSelector(
  (s: AppState) => (s.tokenResponse ? s.tokenResponse.accessToken : null),
  (t: string | null) => {
    if (t === null) {
      return null;
    }
    try {
      return JwtDecode(t);
    } catch (e) {
      return null;
    }
  }
);

If you want to pin the return type manually, declare it on your selector function instead:

const getToken = createSelector(
  (s: AppState) => (s.tokenResponse ? s.tokenResponse.accessToken : null),
  (t: string | null): Token | null => {
    if (t === null) {
      return null;
    }
    try {
      return JwtDecode(t);
    } catch (e) {
      return null;
    }
  }
);

Upvotes: 1

Related Questions