typescript可选参数 null,undefine的表现

程序测试

ts 复制代码
function add(a: number, b?: number | null): number {
    if (b == undefined) {
        console.log("b is empty")
    }
    if (!b) {
        console.log("b is empty x")
    }
    if (b == null) {
        console.log("b is empty y")
    }


    let c = b ?? 0;
    let d = b!;
    console.log(d);
    console.log(c);
    let x = c + a;
    console.log(x)
    return x;
}

测试

在nodejs环境进行测试,都没有奔溃问题

  • 可选参数不传
    add(1)
    // 控制台打印
    // b is empty
    // b is empty x
    // b is empty y
    // undefined
    // 0
    // 1
  • 传undefined
    add(1, undefined)
    // 控制台打印
    // b is empty
    // b is empty x
    // b is empty y
    // undefined
    // 0
    // 1
  • 传null
    // b is empty
    // b is empty x
    // b is empty y
    // null
    // 0
    // 1

总结,上面三种情况都不管是判空,判undefine或者是判非可以匹配到。

相关推荐
chilavert3182 小时前
技术演进中的开发沉思-371:final 关键字(中)
java·前端·数据库
2301_816997882 小时前
Vite构建工具
前端
yuki_uix3 小时前
深入理解 reduce:从面试题到设计思维
前端
凌云拓界3 小时前
TypeWell全攻略(二):热力图渲染引擎,让键盘发光
前端·后端·python·计算机外设·交互·pyqt·数据可视化
coding随想3 小时前
TypeScript 高级类型全攻略:从“可表达性”到“类型体操”的实践之路
前端·javascript·typescript
We་ct3 小时前
LeetCode 222. 完全二叉树的节点个数:两种解法详解(BFS + 二分查找优化)
数据结构·算法·leetcode·typescript
大时光3 小时前
gsap -滚动插件 ScrollTrigger 简单demo
前端
tangbin5830853 小时前
iOS Swift:蓝牙 BLE 连接外设CoreBluetooth
前端