|
| 1 | +/** |
| 2 | + * 根据结构配置生成 TypeScript 类型字符串 |
| 3 | + */ |
| 4 | +export function getTypes( |
| 5 | + composites: { structure: string[]; items: string[][] }, |
| 6 | + commentsMap: Record<string, string> = { |
| 7 | + title: '信息图标题', |
| 8 | + desc: '信息图描述', |
| 9 | + items: '信息图的内容项', |
| 10 | + label: '项目标签文本', |
| 11 | + value: '项目数值内容', |
| 12 | + icon: '项目图标', |
| 13 | + illus: '项目插图', |
| 14 | + children: '子级项目(多层结构)', |
| 15 | + }, |
| 16 | +): string { |
| 17 | + const { structure, items } = composites; |
| 18 | + |
| 19 | + const lines: string[] = []; |
| 20 | + const indent = (level: number) => ' '.repeat(level); |
| 21 | + |
| 22 | + function fieldLine(name: string, type: string, level: number) { |
| 23 | + const comment = commentsMap[name]; |
| 24 | + return comment |
| 25 | + ? `${indent(level)}/** ${comment} */\n${indent(level)}${name}: ${type};` |
| 26 | + : `${indent(level)}${name}: ${type};`; |
| 27 | + } |
| 28 | + |
| 29 | + function buildItemType(level: number, indentLevel: number): string { |
| 30 | + const fields = items[level]; |
| 31 | + const fieldLines: string[] = []; |
| 32 | + |
| 33 | + for (const field of fields) { |
| 34 | + const type = field === 'value' ? 'number' : 'string'; |
| 35 | + fieldLines.push(fieldLine(field, type, indentLevel + 1)); |
| 36 | + } |
| 37 | + |
| 38 | + if (items[level + 1]) { |
| 39 | + fieldLines.push( |
| 40 | + fieldLine( |
| 41 | + 'children', |
| 42 | + `Array<${buildItemType(level + 1, indentLevel + 1)}>`, |
| 43 | + indentLevel + 1, |
| 44 | + ), |
| 45 | + ); |
| 46 | + } |
| 47 | + |
| 48 | + return `{\n${fieldLines.join('\n')}\n${indent(indentLevel)}}`; |
| 49 | + } |
| 50 | + |
| 51 | + lines.push('type InfographicType = {'); |
| 52 | + |
| 53 | + // title / desc |
| 54 | + if (structure.includes('title')) { |
| 55 | + lines.push(fieldLine('title', 'string', 1)); |
| 56 | + lines.push(fieldLine('desc', 'string', 1)); |
| 57 | + } |
| 58 | + |
| 59 | + // items |
| 60 | + if (structure.includes('item') && items.length > 0) { |
| 61 | + lines.push(fieldLine('items', `Array<${buildItemType(0, 1)}>`, 1)); |
| 62 | + } |
| 63 | + |
| 64 | + lines.push('}'); |
| 65 | + |
| 66 | + return lines.join('\n'); |
| 67 | +} |
0 commit comments