如何扩展 Hapi 类型 [Typescript]

Vla*_*kic 2 typescript hapi.js

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

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

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

const server: HapiServer = new Hapi.Server();
Run Code Online (Sandbox Code Playgroud)

它返回的错误服务器无法分配给 HapiServer,类型服务器中缺少属性“seneca”。

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

Mei*_*hes 5

您有几个选择:

投掷:

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

//server.seneca === undefined
Run Code Online (Sandbox Code Playgroud)

联盟

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

延长

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

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

const server: MyHapiServer = new MyHapiServer();
Run Code Online (Sandbox Code Playgroud)