[英]TypeScript typings for package that extends built-in node types
I'm trying to create full typings for https://www.npmjs.com/package/keypress我正在尝试为https://www.npmjs.com/package/keypress创建完整类型
I've got the basic function typed out correctly (I think) but can't figure out how to extend the declaration of process.stdin
as this package does to make IntelliSense happy.我已经正确输入了基本的 function(我认为),但无法弄清楚如何扩展
process.stdin
的声明,因为这个 package 确实让 IntelliSense 高兴。
Specifically, keypress
adds a process.stdin.on('keypress', listener)
event.具体来说,
keypress
添加了一个process.stdin.on('keypress', listener)
事件。 The listener
has signature like (ch: Ch, key?: Key) => void
. listener
器具有类似(ch: Ch, key?: Key) => void
的签名。
I'm not sure if I need to extend the Process
interface or maybe the ReadStream
interface since, in theory if I'm understanding correctly, it could work on any ReadStream
.我不确定是否需要扩展
Process
接口或ReadStream
接口,因为理论上如果我理解正确,它可以在任何ReadStream
上工作。
I'm also not sure if it's possible to inform TypeScript that it's calling keypress()
on a ReadStream
that adds the functionality.我也不确定是否可以通知 TypeScript 它正在添加功能的
ReadStream
上调用 keypress keypress()
。 For instance, preventing access unless keypress()
was called.例如,除非调用
keypress()
,否则阻止访问。 I doubt this is possible but asking in case it could be.我怀疑这是可能的,但询问是否可能。
Here is my current attempt:这是我目前的尝试:
declare module "keypress" {
export default function keypress(stream: NodeJS.ReadStream): void;
export type Ch = any; // TODO
export type Key = {
// TODO
ctrl: any;
name: string;
};
namespace global {
namespace NodeJS {
interface Process {
stdin: NodeJS.ReadStream & {
fd: 0; // From official node types
on(event: "keypress", listener: (ch: Ch, key?: Key) => void): this;
};
}
}
}
}
I've tried a few variations on this but I'd rather not keep shooting blind.我已经尝试了一些变化,但我宁愿不要盲目射击。 Any pointers on this greatly appreciated.
对此的任何指示都非常感谢。 Cheers!
干杯!
Looking at the official node type definitions this is what you are trying to extend: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/process.d.ts#L217查看官方节点类型定义,这是您要扩展的内容: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/process.d.ts#L217
Your approach looks fine to me, however I don't think this can be done at the moment.您的方法对我来说看起来不错,但是我认为目前无法做到这一点。 You can use declaration merging to extend types, but you can't use it to overwrite existing members of types.
您可以使用声明合并来扩展类型,但不能使用它来覆盖类型的现有成员。 Otherwise several type definitions could be in conflict with one another.
否则,多个类型定义可能会相互冲突。
However there is a discussion about implementing a solution here: https://github.com/microsoft/TypeScript/issues/36146但是这里有关于实施解决方案的讨论: https://github.com/microsoft/TypeScript/issues/36146
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.