【问题标题】:why typescript can not infer type of expression为什么打字稿不能推断表达式的类型
【发布时间】:2020-12-27 12:40:05
【问题描述】:

为什么其中一个 sn-ps 给出 TSC 错误而另一个不给出? 它们都产生相同的结果。 nameParts 是一个字符串数组。

  if(nameParts[nameParts.length-1]){

    //error: Type 'string | undefined' is not assignable to type 'string'.
    //   Type 'undefined' is not assignable to type 'string'.
    const lastName:string = nameParts[nameParts.length-1];

  }



  const lastWord = nameParts[nameParts.length-1];
  if(lastWord){
    const lastName:string = lastWord;
  }

【问题讨论】:

    标签: typescript expression type-inference


    【解决方案1】:

    TypeScript 在分析深度上有实际限制。使用const 声明,很容易看出lastWord 不会是undefined,但没有它,TypeScript 需要记住它在nameParts[nameParts.length-1] 上看到了守卫,并且没有可能更改的干预代码nameParts[nameParts.length-1](通过分配给它,使用pop,使用shift,等等等等)。为避免使编译器过于复杂和/或过于缓慢,它在分析中并没有走得太远——尤其是因为如果您愿意,您可以使用 const 的第二种方法。

    【讨论】:

    • 这可能有一个很好的 dupetarget,但我还没有一个很好的用于 TypeScript 问题的 dupetargets 库,还没有找到它......
    • "lastWord" 不能未定义,因为您在“if”中验证它。即使不理想,您仍然可以添加“!”最后排除“未定义”类型。
    • @bossno - 你可以,但是随着代码的发展,这样的断言往往会引入错误(例如,有人在该行代码之前添加了pushpop)。我相信这就是你所说的不理想的意思,但我会比这更进一步。 :-D
    猜你喜欢
    • 2022-09-29
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多