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
:
while TypeScript Playground gives:
the return type of Document.getElementById
should be HTMLElement | null
:
el
before null checking is expected to be of type HTMLElement | null
:
el
after null checking is expected to be of type HTMLElement
as type-narrowed:
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
?
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.
The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist.
According to VS Code Docs:
Typically the first step in any new TypeScript project is to add a
tsconfig.json
file. Atsconfig.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 namedtsconfig.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With