最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I make ESLint warn about possibly unexpected result with indexOf in TypeScript? - Stack Overflow

programmeradmin0浏览0评论

I saw a silly bug in my code, which I think a linter could have prevented.

I currently use this ESLint (v9) config for TypeScript:

// @ts-check

import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';

export default tseslint.config(
  eslint.configs.recommended,
  tseslint.configs.recommended,
  {
    rules: {
      "@typescript-eslint/no-explicit-any": "warn"
    }
  }
);

This code sample shows the issue which the linter didn't identify:

const str: string = "1234";
let hasZero = str.indexOf("0") ? "yes" : "no";
console.log(hasZero);
console.log(`hasZero is '${hasZero}'!`);

This TypeScript code always returns "yes" in this sample.

Someone else proposed to use the "@typescript-eslint/prefer-includes": "error" rule, but it returns all OK in the online ESLint playground site.

I know the solution for the code error (str.indexOf("0") > -1 or even better str.includes("0")), but I want to get the linter warn me when I make such a lazy mistake again.

So, what rule would detect this bad code practice?

发布评论

评论列表(0)

  1. 暂无评论