英文:
Typescript Undefined and ? do not take effect in NestJS (like i haven't use them)
问题
在我的嵌套项目中,我使用了在初始化项目时生成的默认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
  }
}
TypeScript并没有考虑到undefined和?。例如,在下面的代码中,y被推断为string,而不是number | 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
英文:
In my nest project in which I use the default tsconfig.json which was generated when i initiated the project
npm i -g @nestjs/cli // (version ^9.0.0)
nest new project-name
typescript does not take into account undefined and ?.
For example in the bellow code y is inferred as string instead of number | undefined;
const x: number | undefined = undefined;
const y = x; // if i hover const y: number instead of number | undefined
const a: { c?: string } = {};
const b = a.c; // if i hover const b: string instead of 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
  }
}
答案1
得分: 0
你应该将 "strict": true 添加到你的 compilerOptions。
通常情况下,对于这种情况,y 的类型会是 undefined,而 b 的类型会是 string | undefined。
我猜想如果 y 不是 number | undefined,那是因为类型是从前一行的赋值中推断出来的。
英文:
You should add "strict": true to your compilerOptions.
And normally with this y will be of type undefined and b will be string | undefined.
I guess if the y is not number | undefined, it's because the type is inferred from the assignment on the previous line.
答案2
得分: 0
你要找的设置是tsconfig.json中的strictNullChecks。
英文:
The setting you are looking for is strictNullChecks in tsconfig.json.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论