如何使打字稿在失败的非空断言上抛出运行时错误?

时间:2021-05-28 20:56:06

标签: typescript settings assert transpiler non-nullable

是否有设置可以让 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断言或错误?

2 个答案:

答案 0 :(得分:1)

没有。

非空断言专门告诉编译器比它更了解。它纯粹是一种用于管理类型信息的构造。但是,如果您不了解编译器,那么您就必须自己处理。

为了类型安全,最好完全避免这个特性(除了少数情况下,你可以 100% 确定该值是非空的),甚至还有来自 eslint 的帮助,让你知道它在no-non-null-assertion rule


我猜好消息是,如果您断言该值不为空,但它为空,那么您的程序最终可能会在某处崩溃...

答案 1 :(得分:0)

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

相关问题