I've been experimenting with the TypeScript compiler API for transforming TypeScript code, but I'm struggling to find a concise method for adding or removing modifiers in a generic way. The solution I currently have is as follows:
function removeDeclareModifier(s) {
let modifiers;
// Remove declare modifiers
if (s.modifiers) {
modifiers = s.modifiers.filter(m => m.kind !== ts.SyntaxKind.DeclareKeyword);
} else {
return s;
}
switch (true) {
case ts.isVariableStatement(s):
return ts.updateVariableStatement(s, modifiers, s.declarationList);
case ts.isTypeAliasDeclaration(s):
return ts.updateTypeAliasDeclaration(s, s.decorators, modifiers, s.name, s.typeParameters, s.type);
case ts.isInterfaceDeclaration(s):
return ts.updateInterfaceDeclaration(s, s.decorators, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);
case ts.isEnumDeclaration(s):
return ts.updateEnumDeclaration(s, s.decorators, modifiers, s.name, s.members);
case ts.isClassDeclaration(s):
return ts.updateClassDeclaration(s, s.decorators, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);
case ts.isFunctionDeclaration(s):
return ts.updateFunctionDeclaration(s, s.decorators, modifiers, s.asteriskToken, s.name, s.typeParameters, s.parameters, s.type, s.body);
default:
return s;
}
}
However, this approach feels overly verbose and prone to errors if the function signatures change. I came across a suggestion to replace the modifiers array, but unfortunately s.modifiers
is read-only in TypeScript, making that route impossible.
Is there a more efficient way to update modifiers without reconstructing the entire AST node?