简体   繁体   English

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

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

I am using Testing Library + i18next, and trying to pass translations into Testing Library's query methods, but am getting type errors.我正在使用测试库 + i18next,并尝试将翻译传递给测试库的查询方法,但出现类型错误。 However, it works fine if I declare the result of the translate function as a variable.但是,如果我将 translate 函数的结果声明为变量,它就可以正常工作。 Maybe this is by design, or something is off with the types in one of those two libraries?也许这是设计使然,或者这两个库之一中的类型有问题?

See the CodeSandbox here .请参阅此处的 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"));

I think this is because of the type inference algorithm that TS uses.我认为这是因为 TS 使用的类型推断算法。 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).当进行类型推断时,TS 只执行一次,当它需要对泛型函数(i18n.t 是)进行类型推断时,这可能还不够。

You can read some more on this thread .您可以在此线程上阅读更多内容。

What you are doing is splitting the inference and TS can handle this.您正在做的是拆分推理,TS 可以处理这个问题。 You also help the algorithm by providing types so TS doesn't need to do inference (or actually does a better job at it).您还可以通过提供类型来帮助算法,因此 TS 不需要进行推理(或者实际上做得更好)。 Something like this:像这样的东西:

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

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

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