Vladimir Djukic Vladimir Djukic - 2 years ago 179
TypeScript Question

How to extend Hapi types [Typescript]

I am trying to add new type to existsing hapi definitions...
I want to add seneca type... Here is example

interface SenecaMethods {
act: any;
add: any;
}

interface HapiServer extends Hapi.Server {
info: any;
seneca: SenecaMethods;
}

const server: HapiServer = new Hapi.Server();



Error it return Server is not assignable to HapiServer, property
'seneca' missing in type server.


How is possbile to add it seneca methods to Hapi.Server? I can put seneca as optional but I don't want it to be optional....

Answer Source

You have a few options:

cast:

const server: HapiServer = new Hapi.Server() as HapiServer;

//server.seneca === undefined

union

const server: HapiServer = Object.assign(new Hapi.Server(),
    { seneca: { act: "foo", add: "bar" } }
  )

extend

class MyHapiServer extends Hapi.Server {
  info: any;
  seneca: SenecaMethods;

  constructor(){
    super();
    this.seneca = {
      act:"foo", 
      add:"bar",
    }
  }
}

const server: MyHapiServer = new MyHapiServer();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download