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

相关推荐
Sokach3864 分钟前
vue3引入tailwindcss 4.1
前端·css
小奋斗13 分钟前
深入浅出:JavaScript中 三大异步编程方案以及应用
javascript·面试
云水边15 分钟前
vue模版中.gitignore和.prettierrc功能区分
前端
尝尝你的优乐美18 分钟前
封装那些Vue3.0中好用的指令
前端·javascript·vue.js
敲代码的彭于晏20 分钟前
localStorage 不够用?试试 IndexedDB !
前端·javascript·浏览器
chxii23 分钟前
5.4 4pnpm 使用介绍
前端·javascript·vue.js
好好好明天会更好31 分钟前
Vue 中 slot 的常用场景有哪些
前端·vue.js
奔赴_向往1 小时前
【qiankun 踩坑】路由切换回来,子应用 Vuex Store 数据居然还在
前端
米开朗积德1 小时前
项目多文件JSON数值比对
javascript
sorryhc1 小时前
【AI解读源码系列】ant design mobile——Image图片
前端·javascript·react.js