1

A common problem that I've come across with some libraries, like grpc, is that the function interfaces are often the generic any. Is there a way in TypeScript to override any with a specific type?

For example, grpc has the following in the TypeScript definition:

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;
}

Any function that is of ServerUnaryCall will have the same fields, but I want to be able to override request: any with a specific type.

Is there a way to do this, even if it means rewriting the TypeScript definition to make it possible?

nevi_me
  • 2,702
  • 4
  • 24
  • 37
  • 1
    Related: https://stackoverflow.com/questions/48690619/how-can-i-augment-a-property-within-a-third-party-typescript-interface-defined-a – Nathan Friend Feb 22 '18 at 17:15
  • Thanks @NathanFriend, I think that could get me closer. Ideally I'd have liked being able to do something like `myUnaryCall(call: ServerUnaryCall, callback)` where I supply what my type is. I suppose the language doesn't support something like that? – nevi_me Feb 22 '18 at 17:23
  • 1
    TypeScript does support generics, but unfortunately the definition file for the library you're using (`grpc`) doesn't use them. In this case, I think your only option is to write your own version of the definition file. – Nathan Friend Feb 22 '18 at 17:26
  • Better yet create a PR with the fix and submit it to DT for the rest of us :) – Aaron Beall Feb 22 '18 at 18:10

1 Answers1

0

Unfortunately, I don't think there is a way to override an existing TypeScript definition file and change some of its declarations. TypeScript does allow your to augment existing interfaces, but this ability is limited to adding content, not changing existing content.

However, as you mention, you could write your own TypeScript definition file; in this case you would have complete control over all of the types.

Here's some information about the augmentation process I mentioned above: https://www.typescriptlang.org/docs/handbook/declaration-merging.html

Nathan Friend
  • 12,155
  • 10
  • 75
  • 125