Home > Back-end >  How do I use TypeScript typing information from a Node.js package?
How do I use TypeScript typing information from a Node.js package?

Time:12-09

I've read a ton of different variations of this same question, but I just can't wrap my mind around it. I'm using the websocket module (which I've used many times before without TypeScript) and I can't figure out how to type my variables?

I have a function that takes in a WebSocketConnection object, but when I give it the type WebSocketConnection I get a "Cannot find name 'WebSocketConnection'" from TypeScript.

I've installed the @types/websocket package and I can see the index.d.ts file with all the type definitions in it located in ./node_modules/@types/websocket/index.d.ts relative to my tsconfig.json file...

I've tried adding the "typeRoots" option to the tsconfig.json file, as well as "types". I've tried many combination of values but as far as I can tell leaving them off entirely is a better bet, so I've tried that as well. I've also tried many variations of importing data from both the .d.ts file and also the package itself, with no luck of course.

I tried using /// <reference path="node_modules/@types/websocket/index.d.ts" /> also with no luck.

I looked in the .d.ts file and found a very clear declaration of an interface called IStringified that looked like this:

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

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

I'm probably just being really dumb and missing something plainly obvious, but any pointers or advice would be much appreciated! What in the world am I doing wrong?

CodePudding user response:

Types of installed packages are not available globally. They must be imported into each file in order to use them. Don't mess with typeroots or triple slash directives at all, that will only make things worse.

In this particular case, the module exports a connection class, which is probably what you want. It's unfortunate name means to make it it look the class constructor that it really is you should probably rename in on import:

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

And now you can do:

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.

You import the type, then use the type:

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

Playground

  • Related