Why is 'null' removed from return type of Document.getElementById in VS Code?

364 views Asked by At

VS Code Version:

VS Code Version

I'm trying some 'Type Narrowing' Code in VS Code, but VS Code gives a different type of information than TypeScript Playground:

VS Code gives: the return type of Document.getElementById is HTMLElement:

VS Code

VS Code

while TypeScript Playground gives:

the return type of Document.getElementById should be HTMLElement | null: enter image description here

el before null checking is expected to be of type HTMLElement | null:

enter image description here

el after null checking is expected to be of type HTMLElement as type-narrowed:

enter image description here

I have already upgraded the global typescript package to v4.0.2 and set typescript.tsdk to /Users/<username>/.nvm/versions/node/v12.16.3/lib/node_modules/typescript/lib in user settings.json

I have set strict type-checking options to:

    /* Strict Type-Checking Options */
    "strict": true,
    // "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    // "strictBindCallApply": true,
    // "strictPropertyInitialization": true, 
    // "noImplicitThis": true,
    "alwaysStrict": true,

Is there some configuration I was missing in tsconfig.json?

1

There are 1 answers

0
Brhaka On

According to VS Code Docs:

Typically the first step in any new TypeScript project is to add a tsconfig.json file. A tsconfig.json file defines the TypeScript project settings, such as the compiler options and the files that should be included. To do this, open up the folder where you want to store your source and add a new file named tsconfig.json. Once in this file, IntelliSense (Ctrl+Space) will help you along the way.

So, the tsconfig.json file should be located in your project's root directory. Another step to solve your issue is to add "strict": true on your newly created tsconfig.json file.