Skip to content
Advertisement

How to type a JavaScript function with JSDoc + TypeScript?

I’m trying to use tsc with plain, Vanilla JS and I’m stumped on how to declare the type a function.

It seems like it should be this simple:

JavaScript

Edit: /** @type PersonGreet */ is correct. The current behavior is a bug in tsc. The selected answer below gives valid workarounds.

Reduced Test Case

Ignore the fact that someone may want to refactor this into using classes or prototypes or some such – it serves well as a demonstration of the problem.

Repo: https://github.com/BeyondCodeBootcamp/hello-tsc

JavaScript

Incorrectly Typed as “any”

When I run tsc to check it gives an error about an implicit any:

JavaScript
JavaScript

What to do?

To me this seems like a bug in tsc… but this is JS 101 stuff, surely there must be a way to type a function?

What annotation do I need to use to declare the function’s type? Or can tsc / tsserver / typescript just not handle this kind of rudimentary use of JS?

Advertisement

Answer

Solution 1

You should use @callback instead of @function like so:

JavaScript

Solution 2

Or, declare a @typedef using typescript syntax like the following:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement