Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript consdering `undefined` as `any` – why?

Here’s my code:

const x = { a: 1, b: undefined }

// x.b is being considered `any` instead of `undefined`

Here’s a screenshot demoing the problem:

A screenshot of VSCode an X variable that has an object assigned to it, composed of two properties: a that is 1, and b that is undefined. The screenshot also displays the error, which is TypeScript understanding b, which is undefined, as any.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In the playground, it is working properly, which leads me to think it is something related to my config. But what could be causing it?

For what it’s worth, this is my tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "rootDir": ".",
    "baseUrl": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "importHelpers": true,
    "target": "ESNext",
    "module": "esnext",
    "lib": ["ESNext", "dom", "DOM.Iterable"],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
  },
  "exclude": ["node_modules", "tmp"]
}

Some extra info:

  • TypeScript version: 4.7.4
  • Editor: VSCode 1.70.1
  • OS: MacOS Monterey 12.0.1

>Solution :

Here is a reproduction of your code in the TypeScript Playground with your TSConfig applied:

const x = { a: 1, b: undefined }
x.b
//^? (property) b: any

and here is the same code with strictNullChecks enabled:

Playground

const x = { a: 1, b: undefined }
x.b
//^? (property) b: undefined

The documentation for strictNullChecks includes this information:

When strictNullChecks is false, null and undefined are effectively ignored by the language. This can lead to unexpected errors at runtime.

Because the type of x.b is undefined, there is no type information remaining after the exclusion of the types above, so the only remaining options are any and never, and because you have disabled strict settings as well, you are left with any.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading