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

相关推荐
wuk9987 分钟前
Webpack技术深度解析:模块打包与性能优化
前端·webpack·性能优化
Moment28 分钟前
Cursor 2.0 支持模型并发,我用国产 RWKV 模型实现了一模一样的效果 🤩🤩🤩
前端·后端·openai
狂炫冰美式37 分钟前
QuizPort 1.0 · 让每篇好文都有测验陪跑
前端·后端·面试
咋吃都不胖lyh1 小时前
.docx 和 .doc 是 Microsoft Word 文档的两种主要文件格式
前端·html·xhtml
哈乐1 小时前
网工应用题:配置命令补全类题目
服务器·前端·网络
uuai1 小时前
echarts不同版本显示不一致问题
前端·javascript·echarts
自然 醒1 小时前
企业微信自建应用开发详细教程,如何获取授权链接?如何使用js-sdk?
javascript·vue.js·企业微信
AKclown1 小时前
基于Monaco的diffEditor实现内容对比
前端·vue.js·react.js
Moonbit2 小时前
MoonBit Pearls Vol.12:初探 MoonBit 中的 Javascript 交互
javascript·后端·面试
chenbin___2 小时前
react native中 createAsyncThunk 的详细说明,及用法示例(转自通义千问)
javascript·react native·react.js