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 分钟前
IconFontViewer -- 一个可以在 Android Studio 中实时预览 IconFont 的插件
android·前端·intellij idea
空中海28 分钟前
03 渲染机制、性能优化与现代 React
javascript·react.js·性能优化
ChalesXavier1 小时前
Fetch API 的基本用法
javascript
是上好佳佳佳呀1 小时前
【前端(十三)】JavaScript 数组与字符串笔记
前端·javascript·笔记
巴沟旮旯儿1 小时前
vite项目配置文件和打包
前端·设计模式
彩票管理中心秘书长1 小时前
Pinia 插件架构与组合式函数:如何让你的 Store 长出“超能力”
前端
彩票管理中心秘书长1 小时前
Pinia 比 Vuex 强在哪?我用同一个模块写了两种实现,你自己看
前端
yingyima1 小时前
用 Cron 加 Webhook 打通自动化工作的任督二脉
前端
JackieDYH1 小时前
CSS Flexbox 与 Grid 的默认行为-布局的底层机制
前端·css·html