函数参数解构前必须兜底为默认空对象,否则传入undefined或null会直接报错;正确写法是function fn({id=0}={}){},嵌套结构需逐层设默认值,null需用??或判空处理,并建议配合JSDoc或TypeScript类型提示。

函数参数对象解构时传入 undefined 会直接报错,不是变量值为 undefined,而是根本无法开始解构——因为 undefined 不满足对象结构要求。关键在解构前兜底,而不是只靠参数默认值。
必须给整个参数设默认空对象
解构的目标必须是对象(或 null/undefined 以外的值),否则一进函数就崩:
-
错误写法:
function getUser({ id, name }) { ... }—— 调用getUser()或getUser(undefined)直接报Cannot destructure property 'id' of 'undefined' -
正确写法:
function getUser({ id = 0, name = '' } = {}) { ... }——= {}拦住undefined,再在内部设字段默认值
嵌套字段要逐层设默认值
如果参数里有深层结构(比如 user.profile.avatar),光靠外层 = {} 不够,中间层缺失仍会报错:
- 安全写法:
function renderUser({ profile = {}, profile: { avatar = '/default.png' } = {} } = {}) { ... } - 等价但更清晰的拆分:
function renderUser(raw = {}) { const { profile = {} } = raw; const { avatar = '/default.png' } = profile; }
null 需要提前归一化
默认值只对 undefined 生效,null 会原样透传,导致后续解构失败:
- 传入
getUser(null),= {}不起作用(因为null !== undefined) - 稳妥方案:用空值合并操作符预处理:
function getUser(opts = {}) { const config = opts ?? {}; const { id = 1, mode = 'view' } = config; } - 或者封装校验:
function getUser(raw) { const config = raw == null ? {} : raw; const { id = 1 } = config; }
配合类型提示提升可维护性
解构本身不检查类型,但加 JSDoc 或 TypeScript 能提前暴露问题:
- JSDoc 示例:
/** @param {{id?: number, name?: string}} config */ function getUser({ id = 0, name = '' } = {}) { ... } - TypeScript 更直接:
function getUser({ id = 0, name = '' }: { id?: number; name?: string } = {}) { ... }
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











