首页 » 网站推广 » phpmysql输出问号技巧_TypeScript中变量调用时后缀感叹号和问号的差异

phpmysql输出问号技巧_TypeScript中变量调用时后缀感叹号和问号的差异

访客 2024-11-16 0

扫一扫用手机浏览

文章目录 [+]

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的方法时,增加后缀!和?时,这个编译缺点都会消逝:

phpmysql输出问号技巧_TypeScript中变量调用时后缀感叹号和问号的差异

x!.toUpperCase() x?.toUpperCase()

那这两者到底有什么差异呢?

phpmysql输出问号技巧_TypeScript中变量调用时后缀感叹号和问号的差异
(图片来自网络侵删)

后缀是?

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')

结论:

后缀是!,只是见告typescript编译器对付null和undefined不做显示的检讨,天生的js文件中还是x.toUpperCase(),如果此时x为null,那么就会涌现运行时非常后缀是?,代表是一个空判断,只有非空是,才会实行x.toUpperCase(),天生的js文件中是增加了null或者undefined判断的,天生的js是(x === null || x === void 0 ? void 0 : x.toUpperCase())

相关文章