ts-morph#ts TypeScript Examples

The following examples show how to use ts-morph#ts. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: enum-mapping.ts    From selling-partner-api-sdk with MIT License 6 votes vote down vote up
function processEnumNodes(sourceFile: SourceFile, nodes: TypeElementTypes[]): void {
  for (const node of nodes) {
    // TODO: implement for a node has union and intersection of enum type. Such as: Enum1 | Enum2, Enum1 & Enum2.
    const typeReference = node.getFirstChildByKind(ts.SyntaxKind.TypeReference)
    const enumNode = typeReference && sourceFile.getEnum(typeReference.getText())
    const enumMembers = enumNode && enumNode.getMembers()

    if (typeReference && enumMembers) {
      const filePath = `${sourceFile.getDirectory().getBaseName()}/${sourceFile.getBaseName()}`
      const typeName = typeReference.getText()
      log.info(`Starting mapping ${typeName} in ${filePath}`)

      // TODO: remove duplicate elements if a node has union and intersection of enum type.
      typeReference.replaceWithText([typeName, ...getEnumValues(enumMembers)].join(' | '))

      log.info(`Finished mapping ${typeName} in ${filePath}`)
    }
  }
}
Example #2
Source File: enum-mapping.ts    From selling-partner-api-sdk with MIT License 6 votes vote down vote up
function processArrayNodes(sourceFile: SourceFile, nodes: TypeElementTypes[]): void {
  for (const node of nodes) {
    /**
     * Check both Array<T> and T[] syntax.
     *
     * Docs: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#arrays
     * TODO: implement for a node has union and intersection of enum type. Such as: Enum1 | Enum2, Enum1 & Enum2.
     */
    const child =
      node.getFirstChildByKind(ts.SyntaxKind.TypeReference) ||
      node.getFirstChildByKind(ts.SyntaxKind.ArrayType)
    const typeReference = child?.getFirstChildByKind(ts.SyntaxKind.TypeReference)
    const enumMembers = typeReference && sourceFile.getEnum(typeReference.getText())?.getMembers()

    if (child && typeReference && enumMembers) {
      const filePath = `${sourceFile.getDirectory().getBaseName()}/${sourceFile.getBaseName()}`
      const typeName = child.getText()
      log.info(`Starting mapping ${typeName} in ${filePath}`)

      /**
       * Wrap inside a block for all array syntax.
       * TODO: remove duplicate elements if a node has union and intersection of enum type.
       */
      typeReference.replaceWithText(
        `(${[typeReference.getText(), ...getEnumValues(enumMembers)].join(' | ')})`,
      )

      log.info(`Finished mapping ${typeName} in ${filePath}`)
    }
  }
}