Home > Back-end >  TypeScript not inferring function argument type when passing inline function call
TypeScript not inferring function argument type when passing inline function call

Time:05-27

I am using Testing Library i18next, and trying to pass translations into Testing Library's query methods, but am getting type errors. However, it works fine if I declare the result of the translate function as a variable. Maybe this is by design, or something is off with the types in one of those two libraries?

See the CodeSandbox here.

import { screen } from "@testing-library/dom";
import i18n from "i18next";

// This works
const translation = i18n.t("my.translation.string");
screen.getByText(translation);

// This does not:
// Argument of type 'TFunctionResult' is not assignable to parameter of type 'Matcher'.
// Type 'undefined' is not assignable to type 'Matcher'.
screen.getByText(i18n.t("my.translation.string"));

CodePudding user response:

I think this is because of the type inference algorithm that TS uses. It seems that they don't use an unification based algorithm.

When doing type inference TS does only one pass and this may not be enough when it needs to to type inference on a generic function (which i18n.t is).

You can read some more on this thread.

What you are doing is splitting the inference and TS can handle this. You also help the algorithm by providing types so TS doesn't need to do inference (or actually does a better job at it). Something like this:

screen.getByText(i18n.t<string>("my.translation.string"));
  • Related