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

相关推荐
石小石Orz9 小时前
星云SDK + 油猴:给LLM塑造肉身,陪伴你在每个网页
前端·人工智能
2601_963771379 小时前
10 Best PHP Media CMS and Scripts for Web Creators in 2026
开发语言·前端·php
VaJoy9 小时前
全面革新⚡️ Vue 3.6 项目工程的基础实现
前端·vue.js
苍何10 小时前
耗时 7 天,我们开源了腾讯 WorkBuddy 实战蓝皮书(建议收藏)
前端·后端
大家的林语冰10 小时前
😭 Electron 麻了,Deno 直接支持二进制应用,无需第三方桌面应用框架!
前端·javascript·node.js
Ivanqhz10 小时前
NFM(神经因子分解机)
开发语言·javascript·人工智能·算法·蓝桥杯
Damai11 小时前
DOMPurify 完整介绍
前端·面试
随风一样自由11 小时前
【前端+跨域】跨域问题全面解析与解决方案指南
前端·跨域
小帅不太帅11 小时前
我随手发了几张截图,白拿了一个月 AI 顶配会员
前端·github
36岁的我开始学习打篮球11 小时前
外规内化技术架构
前端