如何修改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
相关产品推荐
相关产品推荐

