美文网首页
在 TypeScript 中使用 Assert

在 TypeScript 中使用 Assert

作者: Asuna_随便记录点 | 来源:发表于2020-05-04 19:30 被阅读0次

TypeScript 并不能帮你解决下面的类型问题

function yell(str) {
    if (typeof str !== "string") {
        throw new TypeError("str should have been a string.")
    }
    // Error caught!
    return str.toUppercase();
}

不过现在可以这样定义一个 Asserts

function assert(condition: any, msg?: string): asserts condition {
    if (!condition) {
        throw new AssertionError(msg)
    }
}

asserts condition says that whatever gets passed into the condition parameter must be true if the assert returns (because otherwise it would throw an error). That means that for the rest of the scope, that condition must be truthy. As an example, using this assertion function means we do catch our original yell example.

function yell(str) {
    assert(typeof str === "string");

    return str.toUppercase();
    //         ~~~~~~~~~~~
    // error: Property 'toUppercase' does not exist on type 'string'.
    //        Did you mean 'toUpperCase'?
}

function assert(condition: any, msg?: string): asserts condition {
    if (!condition) {
        throw new AssertionError(msg)
    }
}
image.png

完整参考资料:https://www.typescriptlang.org/docs/handbook/release-notes/overview.html#assertion-functions

相关文章

网友评论

      本文标题:在 TypeScript 中使用 Assert

      本文链接:https://www.haomeiwen.com/subject/iugyghtx.html