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:
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:
const x = { a: 1, b: undefined }
x.b
//^? (property) b: undefined
The documentation for strictNullChecks
includes this information:
When
strictNullChecks
isfalse
,null
andundefined
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
.