繁体   English   中英

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

[英]TypeScript not inferring function argument type when passing inline function call

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

请参阅此处的 CodeSandbox

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 是)进行类型推断时,这可能还不够。

您可以在此线程上阅读更多内容。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM