【发布时间】: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