Skip to content

Instantly share code, notes, and snippets.

@lomedil
Last active January 27, 2020 10:16
Show Gist options
  • Save lomedil/6da7f43279b0e2c2594fc37a37e0561a to your computer and use it in GitHub Desktop.
Save lomedil/6da7f43279b0e2c2594fc37a37e0561a to your computer and use it in GitHub Desktop.
Notes about typescript definition files for javascript

Typescript definition files for javascript

Declaring functions/callbacks with generics

I have observed some issues when declaring a function with generics related to some parameters.

Just figure out a type defined like this:

interfaces Response { type: string; data: T }

interface Doc { body: string; }

And we want use like this case:

/**@type {ResponseFunc<Doc>}*/
function handler(response){  // <-- intellisense type have to be 'Response<Doc>'
  response.data                 <-- intellisense type have to be 'Doc'
  ...code...
}

If ResponseFunc<T> is defined like function:

declare function ResponseFunc<T>(Response<T>):void; // as classic function
type ResponseFunc = <T>(res: Response<T>): void;  // as arrow function

Type of parameter is shown like Response<T>. Generic type is not resolved.

If ResponseFunc<T> is defined like type object:

type ResponseFunc<T> = {
  function(Response<T>) : void;
}

Generic is resolved but parameter is show as any instead of Doc.

We need to merge this two ways to resolve the generic type and show parameter with right type.

type ResponseFunc<T> =  {
  (response: Response<T>) : void;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment