首页 > 解决方案 > 返回值存在的类型脚本类型保护

问题描述

我有一个类的方法

isReadyToSumNumbers() {
    return Boolean(
      this.arithmeticOperation && this.slots["1"] && this.slots["2"]
    );
  }

这显然表明如果所有 3 个值都存在,则返回 true。

然后我有另一种使用此方法的方法,如下所示:

if (this.isReadyToSumNumbers()) {
      const newValue = this.arithmeticOperation(
        this.slots["1"],
        this.slots["2"]
      ).toString();
...

但是打字稿显示了一个错误,this.arithmeticOperation can be undefined因此我想进行类型保护,但所有示例都无关紧要,因为您可以键入保护类 | .

我想知道它是怎么做到的。

标签: javascripttypescriptclass

解决方案


最好的选择是内联检查。Typescript 可以比隐藏在方法中的检查更好地找出内联检查。

另一种选择是使用自定义类型保护并使用类型保护更改this类型:

class Test {
    isReadyToSumNumbers(): this is Test & {
        arithmeticOperation: (a: number, b: number) => number;
        slots: {
            1: number,
            2: number
        }
    } {
        return Boolean(
            this.arithmeticOperation && this.slots["1"] && this.slots["2"]
        );
    }
    m() {
        if (this.isReadyToSumNumbers()) {
            const newValue = this.arithmeticOperation(
                this.slots["1"],
                this.slots["2"]
            ).toString();
        }
    }

    arithmeticOperation?: (a: number, b: number) => number;
    slots: {
        1?: number,
        2?: number
    }
}

推荐阅读