Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 397
aztack Avatar asked Oct 24 '20 10:10

aztack


People also ask

Why does my document getElementById returning NULL?

This error TypeError: document. getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.

What does getElementById return if not found?

The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist.


1 Answers

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.

like image 78
Brhaka Avatar answered Sep 17 '22 08:09

Brhaka