使用:not与:has选择器时出现SyntaxError,ESLint规则项目内无法生效
解决ESLint no-restricted-syntax规则的语法错误
我配置了ESLint的no-restricted-syntax规则,期望强制使用Nullable<T>替代| null、Undefinable<T>替代| undefined、Nilable<T>替代| null | undefined。该规则在typescript-eslint playground中可正常运行,但本地项目执行时出现如下语法错误:
SyntaxError: Syntax error in selector ":not(TSTypeAliasDeclaration:has(> Identifier[name=Nullable])):has(> TSUnionType:has(> TSNullKeyword):not(:has(> TSUndefinedKeyword)))" at position 32: Expected " ", "!", "#", "*", ".", ":", ":first-child", ":has(", ":last-child", ":matches(", ":not(", ":nth-child(", ":nth-last-child(", "[", or [^ [],():#!=><~+.] but ">" found.
相关配置文件
package.json(简化版)
{ "devDependencies": { "eslint": "^9.26.0", "typescript": "^5.5.4", "typescript-eslint": "^8.33.1", }, }
.eslintrc
{ "parser": "@typescript-eslint/parser", "parserOptions": { "project": "./tsconfig.json" }, "rules": { "no-restricted-syntax": [ "error", { "selector": ":not(TSTypeAliasDeclaration:has(> Identifier[name=Nullable])):has(> TSUnionType:has( > TSNullKeyword):not(:has(> TSUndefinedKeyword)))", "message": "Use `Nullable<T>` utility type instead of `| null`." }, { "selector": ":not(TSTypeAliasDeclaration:has(> Identifier[name=Undefinable])):has(> TSUnionType:has( > TSUndefinedKeyword):not(:has(> TSNullKeyword)))", "message": "Use `Undefinable<T>` utility type instead of `| undefined`." }, { "selector": "TSUnionType:has(> TSNullKeyword):has(> TSUndefinedKeyword)", "message": "Use `Nilable<T>` utility type instead of `| null | undefined`." } ] } }
tsconfig.json
{ "include": ["src"] }
test.ts
type Nullable<T> = T | null; type Undefinable<T> = T | undefined; type Nilable<T> = Nullable<Undefinable<T>>; type x1 = number | null; type x2 = number | undefined; type x3 = number | null | undefined; type x4 = null | number; type x5 = undefined | number; type x6 = null | number | undefined;
问题原因及解决方法
- 问题根源:
.eslintrc配置中,选择器里的>被错误地写成了HTML转义字符>,而ESLint的选择器语法需要直接使用原生的>符号,转义字符会导致语法解析失败;同时消息中的Nullable<T>等转义字符也无需保留。 - 修正步骤:
- 打开
.eslintrc文件,将所有选择器中的>替换为>; - 将消息中的
Nullable<T>、Undefinable<T>、Nilable<T>分别替换为Nullable<T>、Undefinable<T>、Nilable<T>; - 确保选择器语法格式正确,
:has()内部的子选择器格式符合ESLint要求。
- 打开
修正后的.eslintrc规则部分如下:
"rules": { "no-restricted-syntax": [ "error", { "selector": ":not(TSTypeAliasDeclaration:has(> Identifier[name=Nullable])):has(> TSUnionType:has(> TSNullKeyword):not(:has(> TSUndefinedKeyword)))", "message": "Use `Nullable<T>` utility type instead of `| null`." }, { "selector": ":not(TSTypeAliasDeclaration:has(> Identifier[name=Undefinable])):has(> TSUnionType:has(> TSUndefinedKeyword):not(:has(> TSNullKeyword)))", "message": "Use `Undefinable<T>` utility type instead of `| undefined`." }, { "selector": "TSUnionType:has(> TSNullKeyword):has(> TSUndefinedKeyword)", "message": "Use `Nilable<T>` utility type instead of `| null | undefined`." } ] }
当前依赖版本(eslint@9.26.0 + typescript-eslint@8.33.1)是兼容的,修正后即可正常运行规则。
内容的提问来源于stack exchange,提问作者EzioMercer
相关产品推荐
相关产品推荐

