# prefer-type-guard

Rule `sonarjs/prefer-type-guard`. Type predicates should be used

- Source: sonarjs
- Technologies: JavaScript
- Kind: style
- Needs type information: no
- Autofix: yes, in at least one linter
- Reach: 6.2M weekly downloads of presets that enable it
- Trend: +62.1% last quarter
- Rank: #1351 by reach, #652 by growth

## Linters

| Linter | Rule name | Recommended | Autofix | Details | Docs |
| --- | --- | --- | --- | --- | --- |
| ESLint | `sonarjs/prefer-type-guard` | yes | suggestion | package `eslint-plugin-sonarjs` | [docs](https://rules.sonarsource.com/javascript/RSPEC-4322/) |

## Code examples

### Incorrect: the rule reports this

```js
function isSomething(x: BaseType) : boolean { // Noncompliant
  return (<Something>x).foo !== undefined;
}

if (isSomething(v)) {
  (<Something>v).foo();
}
```

### Correct: the rule accepts this

```js
function isSomething(x: BaseType) : x is Something {
  return (<Something>x).foo !== undefined;
}

if (isSomething(v)) {
  v.foo();
}
```

Examples from the ESLint documentation.

## Enable it

### ESLint: `eslint.config.js`

```js
export default [
  {
    rules: {
      "sonarjs/prefer-type-guard": "error",
    },
  },
];
```

## Presets that enable it

| Preset | Linter | Package | Rules | Weekly downloads | Trend |
| --- | --- | --- | --- | --- | --- |
| [SonarJS recommended](https://lintradar.dev/presets/sonarjs-recommended.md) | ESLint | `eslint-plugin-sonarjs` | 230 | 6.2M | +62.1% |

## Related rules

- [sonarjs/prefer-specific-assertions](https://lintradar.dev/rules/sonarjs/prefer-specific-assertions.md): The most specific assertion should be used
- [sonarjs/production-debug](https://lintradar.dev/rules/sonarjs/production-debug.md): Debugging features should not be enabled in production
- [sonarjs/prefer-single-boolean-return](https://lintradar.dev/rules/sonarjs/prefer-single-boolean-return.md): Return of boolean expressions should not be wrapped into an "if-then-else" statement
- [sonarjs/pseudo-random](https://lintradar.dev/rules/sonarjs/pseudo-random.md): Pseudorandom number generators (PRNGs) should not be used in security contexts
- [sonarjs/prefer-regexp-exec](https://lintradar.dev/rules/sonarjs/prefer-regexp-exec.md): "RegExp.exec()" should be preferred over "String.match()"
- [sonarjs/public-static-readonly](https://lintradar.dev/rules/sonarjs/public-static-readonly.md): Public "static" fields should be read-only

---

Web page: https://lintradar.dev/rules/sonarjs/prefer-type-guard. Data from npm and the linters' documentation, collected Dec 4, 2026. Site guide for agents: https://lintradar.dev/llms.txt
