typescripttypesafe-actions

"createAsyncAction" with request that expects no parameters returns a TypeScript error


Creating async action with typesafe-actions where request expects no parameters

import { createAsyncAction } from "typesafe-actions";

export const testAsync = createAsyncAction(
  "TEST_REQUEST",
  "TEST_SUCCESS",
  "TEST_FAILURE"
)<undefined, string, Error>();

returns a TypeScript error in the Redux connect() method even though it's created accordingly to the docs:

Type 'PayloadMetaActionCreator<"TEST_REQUEST", unknown, unknown>' is not assignable to type '() => void'.


Solution

  • The reason for that is missing "strictNullChecks": true rule in the tsconfig (or "strict": true).

    In strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void).

    It's perhaps due to the 2nd part: "the one exception being that undefined is also assignable to void". Without that rule, typesafe-actions expects PayloadMetaActionCreator instead of EmptyActionCreator when type undefined is passed and therefore returns an error.

    edit: It isn't ideal but another solution for such cases is to use alternative syntax:

    export const testAsync = createAsyncAction(
      "TEST_REQUEST",
      "TEST_SUCCESS",
      "TEST_FAILURE"
    )<[undefined, undefined], string, Error>();