如何扩展 Hapi 类型 [Typescript]

How to extend Hapi types [Typescript]

我正在尝试向现有的 hapi 定义中添加新类型... 我想添加 seneca 类型...这是示例

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.

如何将 seneca 方法添加到 Hapi.Server?我可以将 seneca 作为可选的,但我不希望它是可选的....

您有几个选择:

演员表:

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

//server.seneca === undefined

联盟

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

延长

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

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

const server: MyHapiServer = new MyHapiServer();