缺少 TypeScript + NodeJS readline 属性

TypeScript + NodeJS readline property missing

我正在使用 tsc -v 2.4.2 和 Node v6.10.3 使用 TypeScript 开发一个小项目。

我想在 CLI 中捕获按键,所以我尝试 import * as readline from 'readline' 然后稍后使用 readline.emitKeyPressEvents(process.stdin),但它抱怨说 the property emitKeyPressEvents is not found on typeof readline.

我也做过npm install --save @types/node.

这是一个 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);
            }
        });
    }
}

node 类型中确实缺少该方法。它的正确名称实际上是 emitKeypressEvents(有一个小写的 p),但那个也不见了。我认为这是一个简单的疏忽,所以我提交了 PR 添加到 DefinitelyTyped。这可能需要一段时间来处理(如果一切顺利,大约一周),但与此同时,您可以通过向包含 InputManager:

的文件添加本地声明来键入检查您的代码
declare module 'readline' {
  export function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: ReadLine): void;
}