我正在编写一些自定义TSLint规则,发现我不能在TypeScript版本之间依赖(ASTObject).kind
。
例如,在TypeScript 3.4.5
,enum ts.SyntaxKind
ImportDeclaration = 249
和ImportClause = 250
中。
但是在TypeScript中,3.5.3
,enum ts.SyntaxKind
,ImportDeclaration = 250
和ImportClause = 251
。
这打破了我的规则。有没有更好的方法来检测这个问题,或者没有使用目标项目中的枚举和/或导致它们不对齐的配置问题?
我找不到关于它的文档或其他讨论,所以我不确定它是否被忽视(不太可能)或者我没有正确使用它。
export class Rule extends Rules.AbstractRule {
public apply(sourceFile: ts.SourceFile): RuleFailure[] {
for (const statement of sourceFile.statements) {
// statement.kind / ts.SyntaxKind.ImportDeclaration
// is 249 in TypeScript 3.4.5, 250 in TypeScript 3.5.3,
// object property changes for target code, enum stays the same as lint source
if (statement && statement.kind === ts.SyntaxKind.ImportDeclaration) {
const importDeclaration: ts.ImportDeclaration = statement as ts.ImportDeclaration;
// importDeclaration.moduleSpecifier.kind / ts.SyntaxKind.StringLiteral
// 10 in TypeScript 3.4.5, 10 in TypeScript 3.5.3
if (importDeclaration.moduleSpecifier && importDeclaration.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral) {
const moduleSpecifierStringLiteral: ts.StringLiteral = importDeclaration.moduleSpecifier as ts.StringLiteral;
...
}
// importDeclaration.importClause.kind / ts.SyntaxKind.ImportClause
// is 250 in TypeScript 3.4.5, 251 in TypeScript 3.5.3
// object property changes for target code, enum stays the same as lint source
if (importDeclaration.importClause) {
if (importDeclaration.importClause.namedBindings) {
const namedBindings: ts.NamespaceImport | ts.NamedImports = importDeclaration.importClause.namedBindings;
// namedBindings.kind / ts.SyntaxKind.NamedImports
// is 252 in TypeScript 3.4.5, 253 in TypeScript 3.5.3
// object property changes for target code, enum stays the same as lint source
if (namedBindings && namedBindings.kind === ts.SyntaxKind.NamedImports) {
const namedImports: ts.NamedImports = namedBindings as ts.NamedImports;
for (const element of namedImports.elements) {
const importName: string = element.name.text;
...
}
}
}
}
...
}
}
}
}
2条答案
按热度按时间h6my8fg21#
我会说一个很好的尝试是切换到typescript的“is-methods”,比如:
希望有帮助;)
mo49yndu2#
我遇到了同样的问题,在我的npm包中,我试图用
ts.isImportDeclaration(node)
获取导入声明,这对每个节点都返回false,尽管我的文件中显然有导入声明。最终,问题是我的npm包中有一个typescript依赖项,它与我使用该包的应用程序的版本不同。因此,解决方案是更改npm包,使typescript是dev和peer依赖,而不是标准依赖。