Skip to main content

useValidTypeof (since v0.7.0)

This rule is recommended by Rome.

This rule verifies the result of typeof $expr unary expressions is being compared to valid values, either string literals containing valid type names or other typeof expressions

Examples

Invalid

typeof foo === "strnig"
error[js/useValidTypeof]: Invalid `typeof` comparison value
   js/useValidTypeof.js:1:16
  
1  typeof foo === "strnig"
                  ^^^^^^^^ not a valid type name

typeof foo == "undefimed"
error[js/useValidTypeof]: Invalid `typeof` comparison value
   js/useValidTypeof.js:1:15
  
1  typeof foo == "undefimed"
                 ^^^^^^^^^^^ not a valid type name

typeof bar != "nunber"
error[js/useValidTypeof]: Invalid `typeof` comparison value
   js/useValidTypeof.js:1:15
  
1  typeof bar != "nunber"
                 ^^^^^^^^ not a valid type name

typeof bar !== "fucntion"
error[js/useValidTypeof]: Invalid `typeof` comparison value
   js/useValidTypeof.js:1:16
  
1  typeof bar !== "fucntion"
                  ^^^^^^^^^^ not a valid type name

typeof foo === undefined
error[js/useValidTypeof]: Invalid `typeof` comparison value
   js/useValidTypeof.js:1:16
  
1  typeof foo === undefined
                  ^^^^^^^^^ not a string literal

Suggested fix: Compare the result of `typeof` with a valid type name
    | @@ -1 +1 @@
0   | - typeof foo === undefined
  0 | + typeof foo === "undefined"

typeof bar == Object
error[js/useValidTypeof]: Invalid `typeof` comparison value
   js/useValidTypeof.js:1:15
  
1  typeof bar == Object
                 ^^^^^^ not a string literal

Suggested fix: Compare the result of `typeof` with a valid type name
    | @@ -1 +1 @@
0   | - typeof bar == Object
  0 | + typeof bar == "object"

typeof foo === baz
error[js/useValidTypeof]: Invalid `typeof` comparison value
   js/useValidTypeof.js:1:16
  
1  typeof foo === baz
                  ^^^ not a string literal

typeof foo == 5
error[js/useValidTypeof]: Invalid `typeof` comparison value
   js/useValidTypeof.js:1:15
  
1  typeof foo == 5
                 ^ not a string literal

typeof foo == -5
error[js/useValidTypeof]: Invalid `typeof` comparison value
   js/useValidTypeof.js:1:15
  
1  typeof foo == -5
                 ^^ not a string literal

Valid

typeof foo === "string"
typeof bar == "undefined"
typeof bar === typeof qux