【问题标题】:NodeJs: read from file with type definitions and write to file as class definitionNodeJs:从具有类型定义的文件中读取并作为类定义写入文件
【发布时间】:2022-04-01 10:46:52
【问题描述】:

我有一个带有类型定义的打字稿文件。我需要查找特定类型名称并将其写入另一个文件,但作为一个类。例如:

type exampleOne = {
    atrA: string
    atrB: number
}
type exampleTwo = {
    atrA: number
    atrB: string
    atrC: string
}

并将 exampleTwo 写入另一个文件:

class exampleTwo {
    atrA: number
    atrB: string
    atrC: string
}

我有这个想法,但不知道如何实现:

  1. 读取文件
  2. 找到我想要的类型名称
  3. 从我要查找的行的开头选择,直到下一个右括号
  4. 将“type”一词替换为“class”并取消等号
  5. 写入另一个文件

【问题讨论】:

    标签: javascript node.js typescript prisma


    【解决方案1】:

    您可能正在寻找这个:https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html

    在这种情况下,也许您正在尝试输入类似这样的内容?

    class exampleTwo {
      atrA: number;
      atrB: string;
      atrC: string;
    
    constructor(atrA: number, atrB: string, atrC: string)
      this.atrA = atrA;
      this.atrB = atrB;
      this.atrC = atrC;
    }
    
    const newExample = new exampleTwo(2, 'hello', 'world');
    

    【讨论】:

    • 不,这不是我需要的。类型已经创建,我无法修改它们。我需要的是生成与类型结构匹配的类。简单的方法应该是扩展类型,但这是不可能的。
    【解决方案2】:

    由于我没有找到解决这个问题的方法,我最终通过在 bash 中制作自己的脚本来解决这个问题。我可以使用 javascript,但我更喜欢 bash:

    # Take as argument a name for reference
    NEW=$1
    
    # Verify argument is passed
    if [ $# -ne 1 ]; then
        echo "One argument is required."
        exit 1
    fi
    
    # Location where the types are
    PRISMA_URL='./node_modules/.prisma/client/index.d.ts'
    
    # Location to save the file
    NEW_DTO_CREATE_URL="./src/dtos/create-"${NEW}".dto.ts"
    
    # Verify if already exists that file
    if [ -f ${NEW_DTO_CREATE_URL} ]; then
        echo "Already exists"
    else
    
      # Get the line number where starts the type I need
      LINE_N=$(grep -nm1 "export type ${NEW}CreateManyInput = {" ${PRISMA_URL} | grep -Po '^[^:]+')
      echo "export class Create${NEW^}Dto {" >> ${NEW_DTO_CREATE_URL}
      # Read all the line content on that line number
      LINE=$(head -n ${LINE_N} ${PRISMA_URL} | tail -1)
    
      # Start the loop. While LINE isn't a closed bracket...
      while [[ ${LINE} != *"}"* ]]; do
          ((LINE_N+=1))
          LINE=$(head -n ${LINE_N} ${PRISMA_URL} | tail -1)
          echo "${LINE}" >> ${NEW_DTO_CREATE_URL}
      done
    fi
    

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 2010-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多