如何解决TypeScript中“并非所有代码路径都返回值”的错误?
解决“not all code paths return a value”错误
错误原因
你的addValues函数仅在if条件满足时存在返回逻辑,当if条件不成立(比如输入为空、未选择收支类型)时,函数没有任何返回值,不符合TypeScript要求的返回类型Obj[] | undefined。
修复步骤
- 补全所有代码路径的返回值:在if分支外添加默认返回值(比如
return undefined) - 修正输入值获取逻辑:
- 输入框的内容要通过
.value属性获取,而非直接操作DOM元素 - 判断输入是否有效应该用
inputValue.value.length,而非inputValue?.length
- 输入框的内容要通过
- 修正数据结构合理性:
checked字段存储布尔值(收支状态)即可,不需要存储DOM元素
修正后的完整代码
public addValues(): Obj[] | undefined { const inputValue = document.getElementById('valor') as HTMLInputElement; const inputNameValue = document.getElementById('nome-valor') as HTMLInputElement; const enterChecked = document.getElementById('entrada') as HTMLInputElement; const leftChecked = document.getElementById('saida') as HTMLInputElement; if (inputValue.value.length && inputNameValue.value.length && (enterChecked.checked || leftChecked.checked)) { const list: Obj = { id: Math.random(), valor: +inputValue.value, nomeValor: inputNameValue.value, checked: enterChecked.checked }; if (this.valores == undefined) { this.valores = [list]; return this.valores; } this.valores = [...this.valores, list]; return this.valores; } // 补全不满足条件时的返回值 return undefined; }
额外说明:原代码中return this.valores = [list]的写法虽能运行,但先赋值再返回更清晰;如果是往已有数组添加元素,建议用扩展运算符[...this.valores, list],避免直接覆盖之前的列表数据。
内容的提问来源于stack exchange,提问作者Murilo Nellis
相关产品推荐
相关产品推荐

