【问题标题】:Declare that a method throws error in typescript?声明一个方法在打字稿中引发错误?
【发布时间】:2015-12-23 16:17:07
【问题描述】:

以下内容编译时不会出现错误“声明类型既不是 void 也不是任何必须返回值或由单个 throw 语句组成的函数”。

有没有办法让编译器识别 _notImplemented 抛出异常?

function _notImplemented() {
   throw new Error('not implemented');
}

class Foo {
    bar() : boolean { _notImplemented(); }

我能看到的唯一解决方法是使用泛型。但这似乎有点hacky。有没有更好的办法?

function _notImplemented<T>() : T {
   throw new Error('not implemented');
}

class Foo {
    bar() : boolean { return _notImplemented(); }

【问题讨论】:

    标签: typescript1.7


    【解决方案1】:

    您可以使用 Either 而不是 throw。

    Either 是一种通常保存错误或结果的结构。因为它和其他类型一样,TypeScript 可以很容易地使用它。

    例如:

    function sixthCharacter(a: string): Either<Error, string> {
        if (a.length >= 6) {
            return Either.right<Error, string>(a[5]);
        }
        else {
            return Either.left<Error, string>(new Error("a is to short"));
        }
    }
    

    使用函数sixthCharacter 的函数可以选择解包、返回可能自身、自身抛出错误或其他选项。

    您需要选择一个包含 Either 的库 - 看看像 TsMonad 或 monet.js 这样的 monad 库。

    【讨论】:

    • 我正在与旧版软件交互。我不能使用任何一个
    • 要么来自某个库,你可以安装一个库。
    【解决方案2】:

    你可以指定_notImplemented返回类型never

    never 是永远不会返回的函数的特殊类型。可能是因为无限循环,也可能是因为它总是抛出错误。

    function _notImplemented() : never {
         throw new Error("not Implemented")
    }
    

    【讨论】:

    • 是的。仅当函数仅抛出时,您的答案才有效。如果一个函数通常返回没有错误,但偶尔会抛出,我们不能使用 never (禁用该函数),但我们仍然需要某种注释。这就是 throws 子句的重点。
    • 当然,我假设函数“_notImplemented”仅按照 OP 用例的要求抛出。代码中的错误不是未声明 throws,而是 notImplemented 预计会根据放置位置返回多个内容。通过让它永远不会返回,它将以打字稿的方式正确地解决这个问题。当然,它没有记录函数可以抛出什么。为此,typescript 不够用,如果可能的话,使用 Monadic Either 可能是一个更好的错误管理系统。
    【解决方案3】:

    AFAIK 目前没有非 hacky 的方法来处理这个问题。

    TypeScript 团队目前正在 github (https://github.com/Microsoft/TypeScript/issues/1042) 上对此进行检查,我们很快就会有一些解决方案。

    【讨论】:

      猜你喜欢
      • 2017-02-14
      • 2013-01-22
      • 1970-01-01
      • 2019-03-25
      • 2019-02-12
      • 1970-01-01
      • 2016-10-13
      • 2021-11-10
      • 2017-06-25
      相关资源
      最近更新 更多