网站搜索

如何为 TypeScript 的某些函数的类型参数创建自定义 eslint 规则


我想要求在我的 TypeScript/React 应用程序中将类型参数传递给某些函数(尽管我认为这个问题与 React 无关,我使用 react-hook-form 的上下文钩子作为一个例子)。

例如,这是允许的,并且不会产生 eslint 错误。

const form = useFormContext();

然而,这个例子包括类型参数,并提供了实质性的类型安全性

const form = useFormContext<MyFormType>();

我的问题是,如何编写自定义的 eslint 规则,以强制某些函数必须有类型参数(例如此示例中的 useFormContext)?

答案#1

我自己还在弄清楚,但我有一个使用 eslint-local-rules 和 eslint-typescript 的可行方案,分享出来以防对你有用:

在 eslint-local-rules.js 中:

const { ESLintUtils } = require('@typescript-eslint/utils')

module.exports = {
  'rhf-require-types': {
    meta: {
      docs: {
        description: 'useFormContext must have type',
      },
      schema: [],
    },
    create(context) {
      const services = ESLintUtils.getParserServices(context)

      return {
        CallExpression(node) {
          const { callee } = node

          // These are the types we expect a type argument for
          const typesExpected = [
            'useForm',
            'useFormContext',
          ]

          if (!typesExpected.includes(callee.name)) return null

          const tsNode = services.esTreeNodeToTSNodeMap.get(node)

          if (!tsNode.typeArguments) {
            context.report({
              node: callee,
              message: `${callee.name} should have a type argument`,
            })
          }

          return null
        },
      }
    },
  },
}

然后将 'local-rules/rhf-require-types': 'warn' 添加到你的 .eslintrc 中。