node.js - Thuộc tính readline của TypeScript + NodeJS bị thiếu
Tôi đang làm việc trên một dự án nhỏ bằng TypeScript với tsc -v 2.4.2 và Node v6.10.3.
Tôi muốn ghi lại các phím nhấn trong CLI, vì vậy tôi đã thử import * as readline from 'readline' và sau đó sử dụng readline.emitKeyPressEvents(process.stdin), nhưng nó báo rằng không tìm thấy thuộc tính emitKeyPressEvents trên typeof readline.
Tôi cũng đã thực hiện npm install --save @types/node.
Đây là một M(N)WE:
import * as readline from "readline";
import {SIGINT} from "constants";
export class InputManager
{
private _currentStates: Array<IKeyEntity>;
private _oldStates: Array<IKeyEntity>;
public constructor()
{
// Throws error, won't compile
readline.emitKeyPressEvents(process.stdin);
}
public handleInput()
{
if (process.stdin.isTTY)
process.stdin.setRawMode(true);
process.stdin.on('keypress', (str: string, key: any) => {
process.stdout.write('Handling keypress ['+str+']');
if (key && key.ctrl && (key.name == 'c' || key.name == 'l'))
{
process.kill(process.pid, SIGINT);
}
});
}
}
Câu trả lời #1
Phương thức thực sự đang thiếu trong các kiểu node. Tên đúng của nó thực ra là emitKeypressEvents (với chữ p viết thường), nhưng phương thức đó cũng đang thiếu. Tôi đoán đây chỉ là một sự sơ sót đơn giản, nên tôi đã gửi một PR với phần bổ sung vào DefinitelyTyped. Việc này có thể mất một thời gian để xử lý (khoảng một tuần, nếu mọi việc suôn sẻ), nhưng trong thời gian chờ, bạn có thể kiểm tra kiểu của mã của mình bằng cách thêm một khai báo cục bộ vào tệp chứa InputManager:
declare module 'readline' {
export function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: ReadLine): void;
}
