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或者是判非可以匹配到。

相关推荐
全栈技术负责人20 分钟前
前端团队 AI Core Workflow:从心法到落地
前端·人工智能·状态模式
前端 贾公子40 分钟前
深入浅出 CSS 属性:pointer-events: none
前端·css
曾几何时`41 分钟前
二分查找(十)1146. 快照数组 pair整理
java·服务器·前端
夏河始溢1 小时前
一八二、webpack、grunt、gulp、rollup、parcel、vite 对比介绍
前端·webpack·gulp
别或许1 小时前
python中的异步调用(直接使用教程)
java·前端·python
摘星编程1 小时前
React Native + OpenHarmony:Modal确认取消弹窗
javascript·react native·react.js
xkxnq2 小时前
第四阶段:Vue 进阶与生态整合(第 47 天)(Vue 项目目录结构解析:每个文件夹的作用与规范)
前端·javascript·vue.js
炽烈小老头2 小时前
浏览器渲染原理:从 HTML 到像素的全链路拆解
前端
打小就很皮...2 小时前
React 合同审查组件:按合同原文定位
前端·react.js·markdown