[英]NodeJs: read from file with type definitions and write to file as class definition
我有一个带有类型定义的 typescript 文件。 我需要找到特定的类型名称并将其写入另一个文件,但作为 class。例如:
type exampleOne = {
atrA: string
atrB: number
}
type exampleTwo = {
atrA: number
atrB: string
atrC: string
}
并将 exampleTwo 写入另一个文件:
class exampleTwo {
atrA: number
atrB: string
atrC: string
}
我有这个想法,但我不知道如何实现它:
您可能正在寻找这个: https<\/a> :\/\/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');
由于我没有找到解决这个问题的方法,我最终通过在 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.