typescript编译时,当我们开启严格模式时,下面的代码就会报错:
function doSomething(x: string | null) {
console.log("Hello, " + x.toUpperCase());
}
编译错误:
hello.ts:56:29 - error TS2531: Object is possibly 'null'.
56 console.log("Hello, " + x.toUpperCase());
当我们在调用变量x的方法时,增加后缀!和?时,这个编译错误都会消失:
x!.toUpperCase()
x?.toUpperCase()
那这两者到底有什么区别呢?
后缀是?
function doSomething(x: string | null) {
console.log("Hello, " + x?.toUpperCase());
}
doSomething(null);
输出是:
Hello, undefined
后缀是!
function doSomething(x: string | null) {
console.log("Hello, " + x!.toUpperCase());
}
doSomething(null);
输出是:
Uncaught TypeError TypeError: Cannot read properties of null (reading 'toUpperCase')
结论:
留言与评论(共有 0 条评论) “” |