Babel typescript接口转换为变量



有第三方Props接口:

interface Props {
id: string;
name: string;
age: number;
approval: Approval
}
interface Approval {
signature: string;
}

Props转换成数组的解是什么?

[
{
name: 'id',
type: 'string'
},
{
name: 'name',
type:'string'
},
{
name: 'age',
type: 'number'
},
{
name: 'approval',
type: 'Approval'
}
]

我不知道Typescript的接口可以做到这一点?

更新:也许它不是'转换',不知何故它就像'反映'或其他东西。我能在巴别塔做这个吗?

然而,我只想通过Props得到这个数组。

最后,我通过TS Compile API解决了这个问题:


const {Project, SyntaxKind, Node, PropertySignature} = require('ts-morph');
const {resolve, dirname} = require('path');
let res = {
"Msg": [{
"type": "string",
"name": "type"
}]
}
const project = new Project()
project.addSourceFileAtPath(sourceFilePath)
const sourceFile = project.getSourceFile(sourceFilePath)
const msgInterfaces = sourceFile.getInterfaces()
.filter((interfaceDecl) => {
const interfaceName = interfaceDecl.getName()
return interfaceName.endsWith("SDKType") && !interfaceName.includes("Response")
})
for (const msgInterface of msgInterfaces) {
console.log(sourceFilePath, msgInterface.getName(), 'is building')
const properties = msgInterface.getProperties()
for (const property of properties) {
const propStructure = property.getStructure()
let name = propStructure.name
let type = propStructure.type;
if (BASIC_MSG_EIP712_TYPES[type]) {
res["Msg"].push({
type: BASIC_MSG_EIP712_TYPES[type],
name,
})
continue
}
if (property.getType().isEnum()) {
type = "string"
res["Msg"].push({
type,
name,
})
continue;
}
if (property.getType().isArray()) {
const ele = property.getType().getArrayElementType().getText()
if (!Object.keys(BASIC_MSG_EIP712_TYPES).includes(ele)) continue;
type = BASIC_MSG_EIP712_TYPES[ele] + "[]"
res["Msg"].push({
type,
name
})
continue
}
if (property.getType().getSymbol().getDeclarations()[0].getKind() === SyntaxKind.InterfaceDeclaration) {
type = "Type" + upperCaseFirst(snakeToCamel(name))
res["Msg"].push({
type,
name,
})
const pps = property.getType().getProperties()
res[type] = pps.map(p => {
return {
type: p.getValueDeclaration().getType().getText(),
name: p.getName(),
}
})
continue;
}
}
project.createSourceFile(
`./${dirname(filePath)}/${msgInterface.getName()}EIP712.ts`,
`export const ${msgInterface.getName()}EIP712 = ${JSON.stringify(res, null, 2)} nn`,
{overwrite: true}
)
project.saveSync()
}

相关内容

  • 没有找到相关文章

最新更新