NestJS中TypeScript的Undefined与?未生效问题排查
NestJS项目中TypeScript undefined与可选属性类型推断异常的解决办法
用@nestjs/cli(版本^9.0.0)初始化的NestJS项目,采用默认生成的tsconfig.json时,会碰到TypeScript无法正确识别undefined和可选属性标记?的问题,类型推断完全不符合预期:
const x: number | undefined = undefined; const y = x; // 鼠标悬浮显示const y: number,而非预期的number | undefined const a: { c?: string } = {}; const b = a.c; // 鼠标悬浮显示const b: string,而非预期的string | undefined
当前使用的tsconfig.json配置如下:
{ "compilerOptions": { "module": "commonjs", "declaration": true, "removeComments": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "allowSyntheticDefaultImports": true, "target": "es5", "sourceMap": true, "outDir": "./dist", "baseUrl": "./", "incremental": true, "skipLibCheck": true, "strictNullChecks": false, "noImplicitAny": false, "strictBindCallApply": false, "forceConsistentCasingInFileNames": false, "noFallthroughCasesInSwitch": false } }
问题根源
核心原因是配置中的strictNullChecks被设置为false。当这个选项关闭时,TypeScript会自动将undefined和null从所有类型中隐去,不会在类型推断结果里显式体现,导致变量类型被错误收窄。
解决办法
修改tsconfig.json中的strictNullChecks为true:
{ "compilerOptions": { // 其他配置保持不变 "strictNullChecks": true, // 可选:推荐开启strict模式,包含strictNullChecks在内的一系列严格类型检查,符合NestJS官方最佳实践 "strict": true } }
修改完成后,重新查看示例代码的类型推断:
y的类型会正确显示为number | undefinedb的类型会正确显示为string | undefined
内容的提问来源于stack exchange,提问作者prof chaos
相关产品推荐
相关产品推荐

