You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改initialState消除Type 'number|undefined'不可赋值给number的错误?

解决TypeScript类型不匹配错误:'number | undefined'无法赋值给'number'

问题原因

selectedStudent的类型为Student | undefined,使用可选链?.id获取ID时,返回值类型是number | undefined;但当前initialState中studentId被TypeScript推断为number类型,导致赋值时出现类型不兼容错误。

修改initialState的两种方案

方案1:显式指定类型,允许studentId为number或undefined

通过类型注解明确studentId的类型范围,初始值仍保持为0:

const initialState: {
    id: number;
    studentId: number | undefined;
    targets: [];
} = {
    id: 0,
    studentId: 0,
    targets: []
}

const [program, setProgram] = useState(initialState);

方案2:将studentId初始值设为undefined

让TypeScript自动推断studentId的类型为number | undefined:

const initialState = {
    id: 0,
    studentId: undefined,
    targets: []
}

const [program, setProgram] = useState(initialState);

两种方案都无需修改selectedStudent的类型定义,即可消除setProgram({...program,studentId: selectedStudent?.id})的类型错误。

内容的提问来源于stack exchange,提问作者dave_bell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 14:46:01