[英]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.