Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: valid-typeof: always ban undefined #15635

Merged
merged 6 commits into from Mar 5, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions lib/rules/valid-typeof.js
Expand Up @@ -44,6 +44,21 @@ module.exports = {

const requireStringLiterals = context.options[0] && context.options[0].requireStringLiterals;

let globalScope;

/**
* Checks whether the given node represents a reference to a global variable that is not declared in the source code.
* These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables.
* @param {ASTNode} node `Identifier` node to check.
* @returns {boolean} `true` if the node is a reference to a global variable.
*/
function isReferenceToGlobalVariable(node) {
const variable = globalScope.set.get(node.name);

return variable && variable.defs.length === 0 &&
variable.references.some(ref => ref.identifier === node);
}

/**
* Determines whether a node is a typeof expression.
* @param {ASTNode} node The node
Expand All @@ -59,6 +74,10 @@ module.exports = {

return {

Program() {
globalScope = context.getScope();
},

UnaryExpression(node) {
if (isTypeofExpression(node)) {
const parent = context.getAncestors().pop();
Expand All @@ -74,6 +93,8 @@ module.exports = {
}
} else if (requireStringLiterals && !isTypeofExpression(sibling)) {
context.report({ node: sibling, messageId: "notString" });
} else if (sibling.type === "Identifier" && sibling.name === "undefined" && isReferenceToGlobalVariable(sibling)) {
context.report({ node: sibling, messageId: "invalidValue" });
mdjermanovic marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions tests/lib/rules/valid-typeof.js
Expand Up @@ -45,6 +45,7 @@ ruleTester.run("valid-typeof", rule, {
"typeof(foo) == 'string'",
"typeof(foo) != 'string'",
"var oddUse = typeof foo + 'thing'",
"function f(undefined) { typeof x === undefined }",
{
code: "typeof foo === 'number'",
options: [{ requireStringLiterals: true }]
Expand Down Expand Up @@ -136,6 +137,10 @@ ruleTester.run("valid-typeof", rule, {
options: [{ requireStringLiterals: true }],
errors: [{ messageId: "invalidValue", type: "Literal" }]
},
{
code: "if (typeof bar !== undefined) {}",
errors: [{ messageId: "invalidValue", type: "Identifier" }]
},
{
code: "typeof foo == Object",
options: [{ requireStringLiterals: true }],
Expand Down