Dummy Dummy - 8 months ago 8763
TypeScript Question

Typescript server in VSCode incorrectly reports unused private variable

Why does typescript report that the variable is not used even though it is referenced inside

_close()
method?

The weird thing is that if I remove the private keyword, the warning goes away.

Please note that even though it is a warning, it still does not compile.

enter image description here

tsconfig.json


{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"noUnusedLocals": true, <-- This line
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
]
}
}

Answer Source

Typescript is complaining that you never read the variable. Your _close method only sets it. And I think typescript rightly complains, as what's the point of a storing something if you are never interested in using it's value later?

Moreover, the error goes away if you remove the private modifier because then the value can be read by anyone who has an instance of the class. So typescript can no longer verify that the value is never read (since it might be used by others). But with private, it knows only the class methods can access it, so if it doesn't see the value get read anywhere within the class itself, it will produce an error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download