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?

4
  • 1
    Related: stackoverflow.com/questions/48690619/… Commented Feb 22, 2018 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<MyType>, callback) where I supply what my type is. I suppose the language doesn't support something like that? Commented Feb 22, 2018 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. Commented Feb 22, 2018 at 17:26
  • Better yet create a PR with the fix and submit it to DT for the rest of us :) Commented Feb 22, 2018 at 18:10

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.