【问题标题】:TypeScript: Overriding `any` with type in functionsTypeScript:用函数类型覆盖`any`
【发布时间】:2018-02-23 01:31:33
【问题描述】:

我遇到的一些库(例如grpc)的一个常见问题是函数接口通常是通用的any。 TypeScript 中有没有办法用特定类型覆盖 any

例如,grpc 在 TypeScript 定义中具有以下内容:

export class ServerUnaryCall {
  /**
   * Indicates if the call has been cancelled
   */
  cancelled: boolean;

  /**
   * The request metadata from the client
   */
  metadata: Metadata;

  /**
   * The request message from the client
   */
  request: any;

  private constructor();

  /**
   * Get the endpoint this call/stream is connected to.
   * @return The URI of the endpoint
   */
  getPeer(): string;

  /**
   * Send the initial metadata for a writable stream.
   * @param responseMetadata Metadata to send
   */
  sendMetadata(responseMetadata: Metadata): void;
}

ServerUnaryCall 的任何函数都将具有相同的字段,但我希望能够用特定类型覆盖 request: any

有没有办法做到这一点,即使这意味着重写 TypeScript 定义以使其成为可能?

【问题讨论】:

  • 谢谢@NathanFriend,我认为这可以让我更接近。理想情况下,我希望能够做类似myUnaryCall(call: ServerUnaryCall<MyType>, callback) 的事情,我提供我的类型。我想该语言不支持这样的东西?
  • TypeScript 确实支持泛型,但不幸的是,您正在使用的库的定义文件 (grpc) 不使用它们。在这种情况下,我认为您唯一的选择是编写自己的定义文件版本。
  • 最好还是创建一个带有修复程序的 PR 并将其提交给 DT 以供我们其他人使用:)

标签: typescript


【解决方案1】:

不幸的是,我认为没有办法覆盖现有的 TypeScript 定义文件并更改其某些声明。 TypeScript 确实允许您扩充现有界面,但这种能力仅限于添加内容,而不是更改现有内容。

但是,正如您所提到的,您可以编写自己的 TypeScript 定义文件;在这种情况下,您可以完全控制所有类型。

以下是我上面提到的增强过程的一些信息:https://www.typescriptlang.org/docs/handbook/declaration-merging.html

【讨论】:

    猜你喜欢
    • 2021-01-16
    • 2016-03-18
    • 2019-08-17
    • 2018-05-18
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 2018-04-06
    • 2021-05-29
    相关资源
    最近更新 更多