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

1

11

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?

Epiphytotic answered 24/10, 2020 at 10:13 Comment(3)
In the status bar at the bottom of VSCode you should see a TypeScript version number. If you click on that you should see a command prompt. One of the options is "Open TSConfig". Can you select that option and verify it points to the correct file?Felt
@Felt Thanks, problem solved by creating a tsconfig.json at the root of a project with strict set to true.Epiphytotic
If you set strict: true, you don't have to specify the individual flags. See here: typescriptlang.org/tsconfig#strictAtrophy
L
3

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.

Levorotatory answered 10/11, 2020 at 14:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.