How to use ts-morph - 10 common examples

To help you get started, we’ve selected a few ts-morph examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github terotests / ts2redux / dist / src / index.js View on Github external
m.getBody().forEachDescendant(function (node, traversal) {
                                            switch (node.getKind()) {
                                                case ts_morph_1.SyntaxKind.PropertyAccessExpression:
                                                    // could be this.
                                                    if (node.getFirstChild().getKind() === ts_morph_1.SyntaxKind.ThisKeyword) {
                                                        inputSet_1[node.getChildAtIndex(2).print()] = node;
                                                    }
                                                    break;
                                            }
                                        });
                                        var properties_1 = {};
github roblox-ts / roblox-ts / src / compiler / variable.ts View on Github external
}
	} else if ((ts.TypeGuards.isArrayBindingPattern(lhs) || ts.TypeGuards.isObjectBindingPattern(lhs)) && rhs) {
		// binding patterns MUST have rhs
		const names = new Array();
		const values = new Array();
		const preStatements = new Array();
		const postStatements = new Array();
		let rhsStr = compileExpression(state, rhs);

		if (!isCompiledIdentifier(rhsStr)) {
			const id = state.getNewId();
			preStatements.push(`local ${id} = ${rhsStr};`);
			rhsStr = id;
		}

		if (ts.TypeGuards.isArrayBindingPattern(lhs)) {
			const rhsType = rhs.getType();
			if (
				!isArrayType(rhsType) &&
				!isMapType(rhsType) &&
				!isSetType(rhsType) &&
				!isIterableIterator(rhsType, rhs) &&
				!isIterableFunction(rhsType) &&
				(isObjectType(rhsType) || ts.TypeGuards.isThisExpression(rhs))
			) {
				state.usesTSLibrary = true;
				rhsStr = removeBalancedParenthesisFromStringBorders(rhsStr);
				const id = state.getNewId();
				preStatements.push(`local ${id} = ${rhsStr}[TS.Symbol_iterator](${rhsStr});`);
				rhsStr = id;
			}
		}
github VilledeMontreal / workit / packages / workit-cli / src / command / create / task / index.ts View on Github external
async function processHandler(className, contentFile, isBpmn = false) {
  const camelCase = require('camelcase');
  const classNameWithMaj = camelCase(className, { pascalCase: true });
  const classNameSanitized = camelCase(className);
  const project = new Project({
    // Optionally specify compiler options, tsconfig.json, virtual file system, and more here.
    // If you initialize with a tsconfig.json, then it will automatically populate the project
    // with the associated source files.
    // Read more: https://dsherret.github.io/ts-morph/setup/
  });

  if (fs.existsSync(`${localPath}/src/tasks/${classNameSanitized}.ts`)) {
    return Promise.resolve();
  }

  fs.writeFileSync(
    `${localPath}/src/tasks/${classNameSanitized}.ts`,
    contentFile.toString().replace('[CLASSNAME]', classNameWithMaj)
  );
  // tslint:disable: no-console
  const filePath = path.resolve(`${localPath}/src/config/ioc.ts`);
github gregjacobs / js-to-ts-converter / src / create-ts-ast-project.ts View on Github external
export function createTsAstProject( directory: string, options: {
	indentationText?: IndentationText,
	includePatterns?: string[],
	excludePatterns?: string[]
} = {} ) {
	const tsAstProject = new Project( {
		manipulationSettings: {
			indentationText: options.indentationText || IndentationText.Tab
		}
	} );

	// Get all files, and then filter. Was using glob-all and passing all of the
	// globs to the utility, but it takes way too long on large projects because
	// it seems to read the file system multiple times - once for each pattern.
	let files = glob.sync( `${directory}/**/*.+(js|ts|jsx|tsx)`, {
		follow: true   // follow symlinks
	} );

	// First, filter out any path which includes node_modules. We don't want to
	// attempt to parse those as they may be ES5, and we also don't accidentally
	// want to write out into the node_modules folder
	const nodeModulesRegex = /[\\\/]node_modules[\\\/]/;
github anoaland / anoa-cli / src / generators / views / arrow-function-component-generator.ts View on Github external
async generate(args: CreateComponentArgs): Promise {
    const { naming } = this.context

    // processing
    const project = new Project()

    const { location, props, state } = args
    const name =
      args.kind === ViewKindEnum.component
        ? naming.component(args.name)
        : naming.screen(args.name)

    // build view file
    const viewPath = path.join(location, 'index.tsx')
    const viewFile = project.createSourceFile(viewPath)

    // build props as required
    const hasProps = props && props.length
    let propsName: string

    if (hasProps) {
github roblox-ts / roblox-ts / src / utility / type.ts View on Github external
			.some(ancestor => ancestor.getKind() === ts.SyntaxKind.TypeQuery || isTypeStatement(ancestor)) ||
		// if it is a const enum, it is always a type, even if it isn't a type >:)
github roblox-ts / roblox-ts / src / compiler / binary.ts View on Github external
export function compileBinaryExpression(state: CompilerState, node: ts.BinaryExpression) {
	// @ts-ignore;
	const x = node.getText();

	const nodeParent = getNonNullUnParenthesizedExpressionUpwards(node.getParentOrThrow());
	const parentKind = nodeParent.getKind();
	const isStatement = parentKind === ts.SyntaxKind.ExpressionStatement || parentKind === ts.SyntaxKind.ForStatement;

	const opToken = node.getOperatorToken();
	const opKind = opToken.getKind();
	const isEqualsOperation = opKind === ts.SyntaxKind.EqualsToken;

	const lhs = node.getLeft();
	const rhs = getNonNullExpressionDownwards(node.getRight());
	let lhsStr: string;
	let rhsStr: string;

	if (!isEqualsOperation) {
		checkNonAny(lhs);
		checkNonAny(rhs);
	}

	// binding patterns
github airtasker / spot / lib / src / parsers / utilities / type-parser.ts View on Github external
export function parseTypeNode(typeNode: TypeNode): DataType {
  // Type references must be parsed first to ensure internal type aliases are handled
  if (TypeGuards.isTypeReferenceNode(typeNode)) {
    return parseTypeReference(typeNode);
  } else if (TypeGuards.isNullLiteral(typeNode)) {
    return NULL;
  } else if (TypeGuards.isBooleanKeyword(typeNode)) {
    return BOOLEAN;
  } else if (TypeGuards.isStringKeyword(typeNode)) {
    return STRING;
  } else if (TypeGuards.isNumberKeyword(typeNode)) {
    return FLOAT;
  } else if (TypeGuards.isLiteralTypeNode(typeNode)) {
    return parseLiteralType(typeNode);
  } else if (TypeGuards.isArrayTypeNode(typeNode)) {
    return parseArrayType(typeNode);
  } else if (TypeGuards.isTypeLiteralNode(typeNode)) {
    return parseObjectLiteralType(typeNode);
  } else if (TypeGuards.isUnionTypeNode(typeNode)) {
github airtasker / spot / lib / src / neu / parsers / type-parser.ts View on Github external
export function parseType(
  typeNode: TypeNode,
  typeTable: TypeTable,
  lociTable: LociTable
): Result {
  // Type references must be parsed first to ensure internal type aliases are handled
  if (TypeGuards.isTypeReferenceNode(typeNode)) {
    if (typeNode.getType().isArray()) {
      return parseArrayConstructorType(typeNode, typeTable, lociTable);
    }
    return parseTypeReference(typeNode, typeTable, lociTable);
  } else if (TypeGuards.isNullLiteral(typeNode)) {
    return ok(nullType());
    // TODO: discourage native boolean keyword?
  } else if (TypeGuards.isBooleanKeyword(typeNode)) {
    return ok(booleanType());
    // TODO: discourage native string keyword?
  } else if (TypeGuards.isStringKeyword(typeNode)) {
    return ok(stringType());
    // TODO: discourage native number keyword?
  } else if (TypeGuards.isNumberKeyword(typeNode)) {
    return ok(floatType());
  } else if (TypeGuards.isLiteralTypeNode(typeNode)) {
github airtasker / spot / lib / src / parsers / utilities / type-parser.ts View on Github external
function parseTypeReference(
  typeNode: TypeReferenceNode
): ReferenceType | PrimitiveType | CustomPrimitiveType {
  const declaration = getTargetDeclarationFromTypeReference(typeNode);
  const name = declaration.getName();
  if (TypeGuards.isTypeAliasDeclaration(declaration)) {
    const targetTypeNode = declaration.getTypeNodeOrThrow();
    // if the type name is one of of the internal ones ensure they have not been redefined
    if (SPOT_TYPE_ALIASES.includes(name)) {
      if (TypeGuards.isTypeReferenceNode(targetTypeNode)) {
        throw new Error(`Internal type ${name} must not be redefined`);
      } else if (declaration.getType().isString()) {
        switch (name) {
          case "String":
            return STRING;
          case "Date":
            return DATE;
          case "DateTime":
            return DATETIME;
          default:
            throw new Error(`Internal type ${name} must not be redefined`);
        }
      } else if (declaration.getType().isNumber()) {
        switch (name) {
          case "Number":
          case "Float":