【发布时间】: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