TypeScript中如何通过CLI命令行交互创建类实例
实现方案
完全可以通过命令行交互收集用户输入参数,创建指定的Machine类实例,核心逻辑是通过Node.js的能力读取CLI输入,解析校验后传入类构造函数即可,以下是可直接运行的实现:
代码实现
你现有的Machine.ts不需要修改,直接补全index.ts中缺失的CLI交互逻辑即可,这里用Node.js内置模块实现,不需要额外安装第三方依赖:
// index.ts import * as readline from 'node:readline/promises'; import { stdin as input, stdout as output } from 'node:process'; import { Machine } from './Machine'; // 实现清屏方法,兼容Windows和类Unix系统 const clear = () => { process.stdout.write(process.platform === 'win32' ? '\x1Bc' : '\x1B[2J\x1B[3J\x1B[H'); }; // 实现控制台打印方法 const print = (content: string) => { console.log(content); }; // 实现提问方法,接收问题文本和实例创建完成后的回调 const askQuestion = async (query: string, callback: (instance: Machine | null) => void) => { const rl = readline.createInterface({ input, output }); try { const answer = await rl.question(`${query}\n请按「机型 高度 宽度」格式输入,参数用空格分隔:`); // 拆分用户输入,过滤多余空格 const params = answer.trim().split(/\s+/).filter(item => item.length); // 参数数量校验 if (params.length !== 3) { print('参数错误,请输入3个有效值'); callback(null); return; } const [model, heightInput, widthInput] = params; const height = Number(heightInput); const width = Number(widthInput); // 数值类型校验 if (Number.isNaN(height) || Number.isNaN(width)) { print('参数错误,高度和宽度必须为数字'); callback(null); return; } // 校验通过,创建Machine实例 const machine = new Machine(model, height, width); callback(machine); } finally { rl.close(); } }; // 原有启动逻辑 export function start(): void { clear(); print('Welcome to Machine!'); askQuestion(`What is the model, height, and width of your machine?`, (machine) => { if (machine) { print('实例创建成功:'); console.log(machine); // 此处拿到的machine就是你需要的实例,用户输入Xerox 10 10时,等价于const machine = new Machine('Xerox', 10, 10) } }); } // 启动程序 start();
可选优化
- 如果担心用户单次输入三个参数容易出错,可以把提问拆成三次,依次询问机型、高度、宽度,用户每输入一个参数按一次回车即可,不需要记输入格式。
- 如果需要更丰富的交互能力(比如实时校验、默认值、选项选择),可以替换为
prompts、inquirer这类成熟的CLI交互库,核心逻辑不变:收集参数→校验类型→传入构造函数生成实例。 - 运行时可以直接用
tsx index.ts或者ts-node index.ts执行,不需要手动编译TypeScript文件;如果需要编译为JS运行,记得在tsconfig中开启esModuleInterop配置避免模块导入报错。
运行效果示例
Welcome to Machine!
What is the model, height, and width of your machine?
请按「机型 高度 宽度」格式输入,参数用空格分隔:Xerox 10 10
实例创建成功:
Machine { model: 'Xerox', height: 10, width: 10 }
内容的提问来源于stack exchange,提问作者629060311
相关产品推荐
相关产品推荐

