TypeScript 在传递内联函数调用时不推断函数参数类型

TypeScript not inferring function argument type when passing inline function call

我正在使用 Testing Library + i18next,并尝试将翻译传递给 Testing Library 的查询方法,但出现类型错误。但是,如果我将翻译函数的结果声明为变量,它就可以正常工作。也许这是设计使然,或者这两个库之一中的类型有问题?

参见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"));

我认为这是因为TS使用的类型推断算法。他们似乎没有使用基于统一的算法。

当进行类型推断时,TS 只进行一次传递,当它需要对泛型函数(i18n.t 是)进行类型推断时,这可能还不够。

您可以阅读更多相关内容 thread

你所做的是拆分推理,TS 可以处理这个。您还可以通过提供类型来帮助算法,这样 TS 就不需要进行推理(或者实际上做得更好)。像这样:

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