TypeScript: += on private property doesn't count as a read for --noUnusedLocals
TypeScript Version: 2.9.2
Search Terms: –noUnusedLocals += private property
Code tsconfig.json:
{
"compileOnSave": true,
"compilerOptions": {
"target": "es6",
"module": "none",
"noImplicitAny": true,
"removeComments": false,
"outFile": "test.js",
"declaration": false,
"noEmitOnError": true,
"sourceMap": false,
"strictNullChecks": true,
"noUnusedLocals": true,
"noUnusedParameters": true
}
}
test.ts
export class TestClass {
private mNumber: number = 0;
private get Number(): number { return this.mNumber; }
private set Number(value: number) { this.mNumber = value; }
public DoSomething() {
this.Number += 1;
}
}
Result
c:\Temp>tsc
test.ts(3,16): error TS6133: 'Number' is declared but its value is never read.
Expected behavior: += should count as both a read and a write
Actual behavior: += seems to count as a write but not a read. though this problem doesn’t occur with a public property.
Playground Link: I don’t think I can set --noUnusedLocals on the playground
Related Issues: I found this “noUnusedLocals checks don’t work with private modifier”: https://github.com/Microsoft/TypeScript/issues/15775 but it was closed
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 24 (13 by maintainers)
I still feel like this is somewhat questionable - the getter’s value is still never observed outside of the assignment.
Still looks like a code smell to me.
This should be a no-op (if I were to see such a statement without looking at the getter and setter),
But with what you have, it’s an increment operation.
It just seems like a code smell that you would have a private getter only for the
+=
and not actually use the getter anywhere else. Instead, choosing to usemYes
overYes
.In your specific case, sure, you’re actually reading it.
But I think in the more general case, if someone had a getter that was only used for
+=
, they’re probably doing something wrong. Probably.At the moment, TS gives you an error with
--noUnusedLocals
. But TS can be seen as just-a-linter-with-strong-opinions at the end of the day.Making one user use
@ts-ignore
seems safer than opening the gateway to suspicious looking code for everyone else who creates private getters and forgets to actually use them.TS’ goal isn’t to admit all possible safe code. But to admit as much as it can while being dev-friendly. I feel like your request is just not dev-friendly in the general case.
Compiling
+=
without a getter is definitely not ideal, though. Definitely agree on that.