代码之家  ›  专栏  ›  技术社区  ›  rooch84

null的条件检查不适用于函数

  •  0
  • rooch84  · 技术社区  · 5 年前

    function nullOrString(): string | null {
      return null;
    }
    

    这不会产生任何错误:

    const value = nullOrString();
    if (value) {
      const foo: string = value;
    }
    

    但以下情况确实会产生错误 Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.

    if (nullOrString()) {
      const foo: string = nullOrString();
    }
    

    我是对函数有误解,还是这是一个类型脚本错误?

    2 回复  |  直到 5 年前
        1
  •  2
  •   janluke    5 年前

    这不是TypeScript错误。一般来说,即使函数没有参数,也不能保证同一函数在不同调用中返回相同的值(或联合类型的同一子类型的值)。所以TypeScript不会这么认为。

    关于您的代码,第一个调用返回一个truthy值的事实与第二个调用返回的值无关。每个新调用都是TypeScript的新值。

        2
  •  0
  •   masp    5 年前

    当函数返回字符串| null时,只需编写:

    if (nullOrString()) {
        const foo: string | null = nullOrString();
    }
    

    由于nullOrString()可能返回null,因此不能在typescript中以严格模式将其赋给字符串。

    推荐文章