Skip to content

Commit

Permalink
Update: Allow template string in valid-typeof comparison (fixes esl…
Browse files Browse the repository at this point in the history
  • Loading branch information
not-an-aardvark authored and nzakas committed Sep 19, 2016
1 parent f71937a commit 709a734
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/rules/valid-typeof.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,10 @@ module.exports = {
if (parent.type === "BinaryExpression" && OPERATORS.indexOf(parent.operator) !== -1) {
const sibling = parent.left === node ? parent.right : parent.left;

if (sibling.type === "Literal") {
if (VALID_TYPES.indexOf(sibling.value) === -1) {
if (sibling.type === "Literal" || sibling.type === "TemplateLiteral" && !sibling.expressions.length) {
const value = sibling.type === "Literal" ? sibling.value : sibling.quasis[0].value.cooked;

if (VALID_TYPES.indexOf(value) === -1) {
context.report(sibling, "Invalid typeof comparison value.");
}
} else if (requireStringLiterals && !isTypeofExpression(sibling)) {
Expand Down
31 changes: 31 additions & 0 deletions tests/lib/rules/valid-typeof.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,20 @@ ruleTester.run("valid-typeof", rule, {
{
code: "typeof foo === typeof bar",
options: [{ requireStringLiterals: true }]
},
{
code: "typeof foo === `string`",
options: [{ requireStringLiterals: true }],
parserOptions: { ecmaVersion: 6 }
},
{
code: "`object` === typeof foo",
options: [{ requireStringLiterals: true }],
parserOptions: { ecmaVersion: 6 }
},
{
code: "typeof foo === `str${somethingElse}`",
parserOptions: { ecmaVersion: 6 }
}
],

Expand Down Expand Up @@ -111,6 +125,11 @@ ruleTester.run("valid-typeof", rule, {
code: "if (typeof bar == 'umdefined') {}",
errors: [{ message: "Invalid typeof comparison value.", type: "Literal" }]
},
{
code: "if (typeof bar === `umdefined`) {}",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Invalid typeof comparison value.", type: "TemplateLiteral" }],
},
{
code: "typeof foo == 'invalid string'",
options: [{ requireStringLiterals: true }],
Expand All @@ -135,6 +154,18 @@ ruleTester.run("valid-typeof", rule, {
code: "undefined == typeof foo",
options: [{ requireStringLiterals: true }],
errors: [{ message: "Typeof comparisons should be to string literals.", type: "Identifier" }]
},
{
code: "typeof foo === `undefined${foo}`",
options: [{ requireStringLiterals: true }],
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Typeof comparisons should be to string literals.", type: "TemplateLiteral" }]
},
{
code: "typeof foo === `${string}`",
options: [{ requireStringLiterals: true }],
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Typeof comparisons should be to string literals.", type: "TemplateLiteral" }]
}
]
});

0 comments on commit 709a734

Please sign in to comment.