UNPKG

ts-simple-ast

Version:

TypeScript compiler wrapper for AST navigation and code generation.

88 lines (86 loc) 3.58 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const ts = require("typescript"); const callBaseFill_1 = require("./../callBaseFill"); const errors = require("./../../errors"); const manipulation_1 = require("./../../manipulation"); const utils_1 = require("./../../utils"); function TypedNode(Base) { return class extends Base { getType() { return this.global.typeChecker.getTypeAtLocation(this); } getTypeNode() { return this.compilerNode.type == null ? undefined : this.global.compilerFactory.getNodeFromCompilerNode(this.compilerNode.type, this.sourceFile); } getTypeNodeOrThrow() { return errors.throwIfNullOrUndefined(this.getTypeNode(), "Expected to find a type node."); } setType(text) { if (utils_1.StringUtils.isNullOrWhitespace(text)) return this.removeType(); const typeNode = this.getTypeNode(); if (typeNode != null && typeNode.getText() === text) return this; // remove previous type const separatorSyntaxKind = getSeparatorSyntaxKindForNode(this); const separatorNode = this.getFirstChildByKind(separatorSyntaxKind); let insertPos; let childIndex; let insertItemsCount; let newText; if (separatorNode == null) { const identifier = this.getFirstChildByKindOrThrow(ts.SyntaxKind.Identifier); childIndex = identifier.getChildIndex() + 1; insertPos = identifier.getEnd(); insertItemsCount = 2; newText = (separatorSyntaxKind === ts.SyntaxKind.EqualsToken ? " = " : ": ") + text; } else { childIndex = separatorNode.getChildIndex() + 1; insertPos = typeNode.getStart(); insertItemsCount = 1; newText = text; } // insert new type manipulation_1.insertIntoParent({ parent: this, childIndex, insertItemsCount, insertPos, newText, replacing: { textLength: typeNode == null ? 0 : typeNode.getWidth(), nodes: typeNode == null ? [] : [typeNode] } }); return this; } fill(structure) { callBaseFill_1.callBaseFill(Base.prototype, this, structure); if (structure.type != null) this.setType(structure.type); return this; } removeType() { if (this.getKind() === ts.SyntaxKind.TypeAliasDeclaration) throw new errors.NotSupportedError(`Cannot remove the type of a type alias. Use ${"setType"} instead.`); const typeNode = this.getTypeNode(); if (typeNode == null) return this; const separatorToken = typeNode.getPreviousSiblingIfKindOrThrow(getSeparatorSyntaxKindForNode(this)); manipulation_1.removeChildren({ children: [separatorToken, typeNode], removePrecedingSpaces: true }); return this; } }; } exports.TypedNode = TypedNode; function getSeparatorSyntaxKindForNode(node) { switch (node.getKind()) { case ts.SyntaxKind.TypeAliasDeclaration: return ts.SyntaxKind.EqualsToken; default: return ts.SyntaxKind.ColonToken; } } //# sourceMappingURL=TypedNode.js.map