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

相关推荐
小鹿软件办公3 小时前
谷歌 Chrome 终于推出垂直标签页与更智能的阅读模式
前端·chrome
薛定猫AI3 小时前
【技术干货】DeepSeek 新模型实测:多模态 Web 生成能力与工程落地评估
前端
AIBox3653 小时前
codex api 配置教程:安装、鉴权、Windows 环境变量
javascript·人工智能·windows·gpt
Reisentyan3 小时前
[vue3]HTML Learn Data Day 9
前端·vue.js·html
曲幽3 小时前
告别手写 API 胶水代码:FastAPI 与 Vue 的“契约自动机” OpenAPI 实战
python·typescript·vue·fastapi·web·swagger·openapi·codegen
小江的记录本3 小时前
【JEECG Boot】 JEECG Boot 数据字典管理——六大核心功能(内含:《JEECG Boot 数据字典开发速查清单》)
java·前端·数据库·spring boot·后端·spring·mybatis
小江的记录本3 小时前
【JEECG Boot】 JEECG Boot——Online表单 系统性知识体系全解
java·前端·spring boot·后端·spring·低代码·mybatis
John_ToDebug3 小时前
Chromium 页面类型与 IPC 通信机制深度解析
前端·c++·chrome
Fanfffff7204 小时前
前端进阶:从请求竞态到并发控制(系统学习笔记)
前端·笔记·学习
大、男人4 小时前
edge浏览器打开baidu.com很慢,我是如何解决的
前端·edge