Is your rule for a general problem or is it specific to your development style?
General common problem with Typescript language
What does your suggested rule do?
If statements should be specific when the type they are checking is number | undefined
Never use if(variable) always use if(variable != undefined) when variable type is number | undefined
List several examples where your rule could be used
For the following function:
function positiveOrNegativeNumber(): number | undefined
While checking if the result is undefined, it is very common to forget that 0 also returns false.
if(positiveOrNegativeNumber()) is the wrong way to check.
if(positiveOrNegativeNumber() != undefined) is the right way to check.
This rule will probably save tons of unintended bugs and headaches.
Additional context
const a = null
const b = undefined
const c = 0
const d = 1
if(a) console.log(a) // Nothing
if(b) console.log(b) // Nothing
if(c) console.log(c) // Nothing
if(d) console.log(d) // Prints 1
I've not come across a problem but there might a similar need in some string | undefined cases.
Hi @goktugyil! Does the strict-boolean-expression rule not work for you? That was added for what seems like this use case.
Hi @goktugyil! Does the
strict-boolean-expressionrule not work for you? That was added for what seems like this use case.
I had my project at:
"strict-boolean-expressions": true
I also just tried changing it to false and commenting it out and the one below. Nothing changed.
"strict-boolean-expressions": [true, "allow-boolean-or-undefined", "allow-number"],
Here is the test case I used: http://prntscr.com/o2k533
Anything I'm missing?
Perhaps you're using an editor extension/plugin that doesn't support typed rules? https://github.com/Microsoft/vscode-tslint/issues/70#issuecomment-241041929
When I run on the CLI, I do get these errors:
{
"rules": {
"strict-boolean-expressions": [
true,
"allow-boolean-or-undefined",
"allow-number"
]
}
}
const a = null
const b = undefined
const c = 0
const d = 1
if(a) console.log(a) // Nothing
if(b) console.log(b) // Nothing
if(c) console.log(c) // Nothing
if(d) console.log(d) // Prints 1
> tslint -c tslint.json -p tsconfig.json
ERROR: C:/Code/tstest/src/index.ts:8:4 - This type is not allowed in the 'if' condition because it is always falsy. Allowed types are boolean, number, or boolean-or-undefined.
ERROR: C:/Code/tstest/src/index.ts:9:4 - This type is not allowed in the 'if' condition because it is always truthy. It may be null/undefined, but neither 'allow-null-union' nor 'allow-undefined-union' is set. Allowed types are boolean, number, or boolean-or-undefined.
Needed to add this plugin: https://github.com/Microsoft/typescript-tslint-plugin for my editor to show type checking errors.
Thanks, the rule is working for me now!
Most helpful comment
Needed to add this plugin: https://github.com/Microsoft/typescript-tslint-plugin for my editor to show type checking errors.
Thanks, the rule is working for me now!