TypeScript中readline.createInterface识别process.stdin类型错误求助
TypeScript中readline.createInterface类型不匹配问题解决
问题详情
调用readline.createInterface时,TypeScript抛出类型错误:
No overload matches this call. Overload 1 of 2, '(input: ReadableStream, output?: WritableStream | undefined, completer?: Completer | AsyncCompleter | undefined, terminal?: boolean | undefined): Interface', gave the following error. Object literal may only specify known properties, and 'input' does not exist in type 'ReadableStream'.
问题代码:
import * as readline from 'readline'; const rl = readline.createInterface({ input: process.stdin, output: process.stdout, prompt: "> " }); rl.on('line', (line) => { console.log(`got ${line}`); rl.prompt(); }); rl.prompt();
相关版本:
- TypeScript:5.2.2
- Node.js:18.20.4
- @types/node:22.5.2
问题原因
@types/node v22.x 引入了Web标准的ReadableStream类型,与Node.js自身的NodeJS.Readable类型重名。TypeScript解析时错误匹配到Web标准的ReadableStream,而非Node.js的可读流类型,导致参数格式校验失败。
解决方案
方案1:显式类型断言
将process.stdin和process.stdout断言为Node.js内置的流类型:
import * as readline from 'readline'; const rl = readline.createInterface({ input: process.stdin as NodeJS.Readable, output: process.stdout as NodeJS.Writable, prompt: "> " }); rl.on('line', (line) => { console.log(`got ${line}`); rl.prompt(); }); rl.prompt();
方案2:降级@types/node版本
由于@types/node v22对应Node.js 22,而你使用的是Node.js 18,降级到适配Node.js 18的类型包版本:
npm install @types/node@18 --save-dev
方案3:调整tsconfig.json配置
在tsconfig.json中明确指定Node.js类型库,并开启类型库校验跳过,避免冲突:
{ "compilerOptions": { "target": "ES2022", "module": "CommonJS", "lib": ["ES2022"], "types": ["node"], "skipLibCheck": true, "esModuleInterop": true, "strict": true } }
内容的提问来源于stack exchange,提问作者James Richardson
相关产品推荐
相关产品推荐

