面试题答案
一键面试可选链(?.)转换机制
- 成员访问(obj?.prop):
在编译时,TypeScript 会将
obj?.prop
转换为类似于obj === null || obj === undefined? undefined : obj.prop
的 JavaScript 代码。例如:
let obj;
let propValue = obj?.prop;
编译后:
let obj;
let propValue = obj === null || obj === undefined? undefined : obj.prop;
- 函数调用(func?.(args)):
func?.(args)
会被转换为func === null || func === undefined? undefined : func(args)
。例如:
let func;
let result = func?.(1, 2);
编译后:
let func;
let result = func === null || func === undefined? undefined : func(1, 2);
空值合并运算符(??)转换机制
空值合并运算符 a?? b
会被转换为 a!== null && a!== undefined? a : b
。例如:
let a;
let b = 10;
let result = a?? b;
编译后:
let a;
let b = 10;
let result = a!== null && a!== undefined? a : b;
不同运行环境的兼容性和表现差异
- 现代浏览器:
- 主流现代浏览器(如 Chrome、Firefox、Safari 等较新版本)都支持可选链和空值合并运算符。它们能按照预期执行代码,无需额外处理。
- Node.js:
- Node.js 在较新版本(如 Node.js 14+)开始支持这两个运算符。在旧版本中,使用这些运算符会导致语法错误。
在不支持环境中模拟功能
- 模拟可选链:
- 成员访问:
function optionalChain(obj, prop) {
return obj === null || obj === undefined? undefined : obj[prop];
}
// 使用
let obj = { key: 'value' };
let value = optionalChain(obj, 'key');
- 函数调用:
function optionalCall(func,...args) {
return func === null || func === undefined? undefined : func.apply(this, args);
}
// 使用
let func = function(a, b) { return a + b; };
let result = optionalCall(func, 1, 2);
- 模拟空值合并运算符:
function nullishCoalesce(a, b) {
return a!== null && a!== undefined? a : b;
}
// 使用
let a;
let b = 10;
let result = nullishCoalesce(a, b);