如何使用 Node.js 包中的 TypeScript 键入信息?

How do I use TypeScript typing information from a Node.js package?

我已经阅读了同一个问题的大量不同变体,但我就是无法全神贯注。我正在使用 websocket 模块(我以前在没有 TypeScript 的情况下使用过很多次)但我不知道如何输入我的变量?

我有一个接受 WebSocketConnection 对象的函数,但是当我给它类型 WebSocketConnection 时,我从 TypeScript 得到一个 "Cannot find name 'WebSocketConnection'"

我已经安装了 @types/websocket 包,我可以看到 index.d.ts 文件,其中包含所有类型定义,位于 ./node_modules/@types/websocket/index.d.ts 相对于我的 tsconfig.json 文件...

我已经尝试将 "typeRoots" 选项添加到 tsconfig.json 文件,以及 "types"。我已经尝试了许多值的组合,但据我所知,完全不使用它们是更好的选择,所以我也尝试过。我还尝试了 importing 来自 .d.ts 文件和包本身的数据的多种变体,当然没有运气。

我尝试使用 /// <reference path="node_modules/@types/websocket/index.d.ts" /> 也没有成功。

我查看了 .d.ts 文件,发现一个名为 IStringified 的接口的非常清晰的声明如下所示:

export interface IStringified {
    toString: (...args: any[]) => string;
}

所以我尝试访问 IStringified,但我仍然遇到相同的 "Cannot find name 'IStringified'" 错误。

我可能真的很愚蠢,遗漏了一些显而易见的东西,但是任何指点或建议将不胜感激!我到底做错了什么?

安装包的类型在全球范围内不可用。必须将它们导入到每个文件中才能使用它们。根本不要乱用 typeroots 或三重斜杠指令,这只会让事情变得更糟。

在这种特殊情况下,the module exports a connection class,这可能就是您想要的。不幸的是,这个名字意味着让它看起来像 class 构造函数,它确实是你应该在导入时重命名:

import {
  server as WebSocketServer,
  connection as WebSocketConnection,
} from 'websocket'

现在您可以:

const wsServer = new WebSocketServer({ httpServer: server });

wsServer.on('request', function(request) {
  var connection = request.accept('echo-protocol', request.origin);
  doSomethingWithWsConnection(connection) // works
});

function doSomethingWithWsConnection(connection: WebSocketConnection) {
  //...
}

Typesafe example on TS playground


So I tried to access IStringified and I'm still getting the same "Cannot find name 'IStringified'" error.

你导入类型,然后使用类型:

import { IStringified } from 'websocket'
const foo: IStringified = { toString: () => 'asdf' }

Playground