Search code examples
typescriptnestjsnestjs-config

Typescript Undefined and ? do not take effect in NestJS (like i haven't use them)


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
  }
}

Solution

  • 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.