deno_lint icon indicating copy to clipboard operation
deno_lint copied to clipboard

Comparing a literal string union variable to `typeof` throws a `valid-typeof` error

Open AnInternetTroll opened this issue 4 years ago • 4 comments

When I run deno lint --unstable on this typescript I am getting a error

function test(typeTest: "string" | "number" | "boolean", input: any) {
	if(typeTest === typeof input)
		console.log("Yey")
}
(valid-typeof) Invalid typeof comparison value
	if(typeTest === typeof input)
     ^^^^^^^^
    at file.ts:1:64

AnInternetTroll avatar Dec 11 '20 12:12 AnInternetTroll

Thanks for the report! The linter should check typeof comparison only when it's compared to string literals, not variables. I'll fix it.

magurotuna avatar Dec 11 '20 12:12 magurotuna

@bartlomieju Looking at #38, which is the PR that introduced valid-typeof rule, there was a discussion that you adopted a stricter option i.e. "requireStringLiterals": true over the default option in ESLint (actually the default is false).

It seems like @AnInternetTroll's example shows one of the useful and practical usages of typeof comparison with what's not string literals, although typeof foo === undefined still must be a mistake by a programmer in almost all cases. So I'd say it would be great if our valid-typeof behaved as follows:

valid

typeof foo === 'string';
typeof foo == 'undefined';
typeof foo === someVariable; // comparison with normal variables is okay

invalid

typeof foo === 'strign'; // this is typo

// comparison with the literal of `undefined`, `null`, or `Object` are invalid!
typeof foo === undefined;
typeof foo === null;
typeof foo === Object;

Comparison with undefined, null, Object literals are treated as errors, but with other variables are okay. This is a behavior of our own that is different from ESLint.

Any thoughts on this?

magurotuna avatar Dec 11 '20 13:12 magurotuna

Comparison with undefined, null, Object literals are treated as errors, but with other variables are okay. This is a behavior of our own that is different from ESLint.

Of the three items mentioned, only null is a literal, the others are global properties, does that complicate anything?

Will comparisons against all global properties be disallowed? Hopefully, they are, comparing against any of them wouldn't make sense.

ghost avatar Apr 17 '21 20:04 ghost

@magurotuna sorry I completed missed the ping, I agree with your proposed solution.

bartlomieju avatar Aug 24 '21 18:08 bartlomieju