首页 > 解决方案 > Typescript 扩展相同接口的不兼容泛型类型

问题描述

为什么处理函数的请求类型不兼容。我假设 Request 和扩展 Request 的 ApiServerRequest 是兼容的,为什么不呢?

const app = {}
type App = typeof app

const testRoute = {
  method: 'GET',
  path: '',
  options: {
    tags: ['api'],
    description: '',
  },
  handler (request: ApiServerRequest<App>, reply: ResponseToolkit): ResponseObject {
    return reply.view('landing', {
      customerLandingHash: request.params.customerWalletPassId
    })
  }
}

打字稿编译引发错误

代码

import { 
  Server, 
  ServerOptions, 
  Lifecycle, 
  ServerRoute,
  RouteOptions, 
  ResponseToolkit, 
  ResponseObject 
} from '@hapi/hapi'

export class ApiServer<A> extends Server {
  app: A = {} as A

  constructor (options: ServerOptions, app: A) {
    super(options)
    this.app = app
    return this
  }

  route (route: ApiServerRoute<A> | Array<ApiServerRoute<A>>): void {
    super.route(route)
  }
}

export interface ApiServerRequest<A> extends Request {
  server: ApiServer<A>
}

export interface ApiServerRequestHandler<A> extends Lifecycle.Method {
  (request: ApiServerRequest<A>, reply: ResponseToolkit, err?: Error): Lifecycle.ReturnValue
}

export interface ApiServerRoute<A> extends ServerRoute {
  handler: ApiServerRequestHandler<A>,
  options: ApiServerRouteOptions<A>
}

export interface ApiServerRouteOptions<A> extends RouteOptions {
  tags: ['api'] | ['api', string] 
  description: string,
  handler?: ApiServerRequestHandler<A>
}

标签: typescriptgenericstypescript-typingstypescript-genericshapi

解决方案


推荐阅读