Home > Software design >  TypeScript consdering `undefined` as `any` - why?
TypeScript consdering `undefined` as `any` - why?

Time:08-19

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.

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

CodePudding user response:

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.

  • Related