synapse synapse - 3 years ago 201
TypeScript Question

How to augment Node.js classes?

I need to add functionality to existing Node.js class, specifically

Server
. Is it possible to use something along the lines of the following snippet?

import * as net from 'net'

type ShutdownableServer = net.Server & { shutdown(): Promise<void> }

function withShutdown(server: net.Server): ShutdownableServer {
/* ... */
}

Answer Source

Is it possible to use something along the lines of the following snippet?

Yes.

type ShutdownableServer = net.Server & { shutdown(): Promise<void> }

function withShutdown(server: net.Server): ShutdownableServer {
  const result = server as ShutdownableServer; 
  result.shutdown = /*your code*/;
  return result;
}

More

I used an assertion. Docs https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download