【问题标题】:How to make typescript throw runtime error on failed non-null assertion?如何使打字稿在失败的非空断言上抛出运行时错误?
【发布时间】:2021-05-28 20:56:06
【问题描述】:

是否有设置让 typescript 将非空断言编译成引发错误的 javascript?

默认情况下,非空断言被丢弃(playground):

// Typescript:
function foo(o: {[k: string]: string}) {
    return "x is " + o.x!
}
console.log(foo({y: "ten"}))

// Compiled into this js without warnings:
function foo(o) {
    return "x is " + o.x;
}
console.log(foo({ y: "ten" }));
// output: "x is undefined"

我想要一个设置或扩展或使它编译成这样的东西:

function foo(o) {
    if (o.x == null) { throw new Error("o.x is not null") }
    // console.assert(o.x != null) would also be acceptable
    return "x is " + o.x;
}

有没有办法将非空感叹号断言转换为javascript断言或错误?

【问题讨论】:

  • 我想说——不要使用非空断言。您很可能可以以不需要它们的方式重组代码。

标签: typescript settings assert transpiler non-nullable


【解决方案1】:

没有。

非空断言专门告诉编译器比它更了解。它纯粹是用于管理类型信息的构造。但是如果你不知道比编译器更好,那你就得自己处理了。

为了类型安全,最好完全避免这个特性(除了极少数情况,你可以 100% 确定该值不为空),甚至 eslint 提供了一些帮助,让你知道它在no-non-null-assertion rule


我想,好消息是,如果您断言该值不是 null,但它是 null,那么您的程序可能最终会在某个地方崩溃...

【讨论】:

    【解决方案2】:

    一种选择是将您自己的宏编写为宏,使用类似macro-ts 的东西。像这样的功能永远不会出现在 typescript 中,因为该项目专门针对构建时(静态)类型检查,正如 Alex Wayne 解释的那样。

    【讨论】:

      猜你喜欢
      • 2015-06-27
      • 1970-01-01
      • 2020-06-20
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多