【问题标题】:Inferred type in generic functions with strictNullChecks具有 strictNullChecks 的泛型函​​数中的推断类型
【发布时间】:2017-09-22 03:28:25
【问题描述】:

使用 typescript 2.5.2 以下代码无法使用 strictNullChecks 编译:

function ifnull<T>(x: T | null | undefined, def: T): T
{
    return x != null ? x : def;
}

console.log(ifnull(2, 1));

给出错误:

Argument of type '2' is not assignable to parameter of type '1 | null | undefined'.

它似乎推断 T 是 1 而不是数字。当您在没有 strictNullChecks 的情况下进行编译时,它会正确推断出类型 number。我没有足够的信心知道这是 Typescript 中的错误还是预期的行为,所以我更愿意在填写错误报告之前在这里询问。

这是预期的吗?严格推理的基本原理是什么,有没有办法定义 ifnull 而不必将其称为 ifnull&lt;number&gt;(...)ifnull&lt;string&gt;(...)

【问题讨论】:

    标签: typescript


    【解决方案1】:

    TypeScript 的核心贡献者之一@RyanCavanaugh 在this answer 中可能最好地解释了严格推理的基本原理。大多数时候,您不希望 TypeScript 通过推断它们的联合来接受同一类型参数的两种不同类型。不过,我不知道为什么 strictNullChecks 关闭后的行为会有所不同。

    您可以做的一件事是通过使用&amp; {} 来推断delay 第二个参数,如下所示:

    function ifnull<T>(x: T | null | undefined, def: T & {}): T
    {
        return x != null ? x : def;
    }
    
    console.log(ifnull(2, 1)); // okay
    

    希望有所帮助;祝你好运!

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 1970-01-01
      • 2013-03-04
      • 2018-05-15
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      相关资源
      最近更新 更多