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

相关推荐
酉鬼女又兒26 分钟前
零基础快速入门前端DOM 操作核心知识与实战解析(完整汇总版)(可用于备赛蓝桥杯Web应用开发)
开发语言·前端·javascript·职场和发展·蓝桥杯·js
喝拿铁写前端1 小时前
一套面向 Web、H5、小程序与 Flutter 的多端一致性技术方案
前端·架构
yaaakaaang1 小时前
(一)前端,如此简单!---下载Nginx
前端·nginx
牛奶1 小时前
为什么全国人民都能秒开同一个视频?
前端·http·cdn
KongHen022 小时前
uniapp-x实现自定义tabbar
前端·javascript·uni-app·unix
数据潜水员2 小时前
三层统计最小力度的四种方法
javascript·vue.js
汪子熙2 小时前
TS2320 错误的本质、触发场景与在 Angular / RxJS 项目中的系统化应对
前端·javascript·angular.js
我命由我123452 小时前
React - BrowserRouter 与 HashRouter、push 模式与 replace 模式、编程式导航、withRouter
开发语言·前端·javascript·react.js·前端框架·html·ecmascript
Younglina2 小时前
用AI全自动生成连环画?我试了,效果惊艳!
前端·ai编程·claude
Devin_chen2 小时前
ES6 Class 渐进式详解
前端·javascript