Jespertheend
Jespertheend

Reputation: 2280

What is the difference between `(x: number) => void` and `function(number) : void` syntax for parameter types?

When creating a javascript function that takes a callback as argument, I can add types for IntelliSense like so:

/**
 * @param {function(number) : void} cb
 */
function takesCallback1(cb) {}

or like so

/**
 * @param {(x: number) => void} cb
 */
function takesCallback2(cb) {}

What's the difference between the two and which should be used for what situation?

Upvotes: 1

Views: 111

Answers (1)

Jespertheend
Jespertheend

Reputation: 2280

function() : is JSDoc syntax whereas () => is TypeScript syntax. Both are supported by IntelliSense, but the former is only supported inside JSDoc comments.

type TypeScriptSignature = (x: number) => void;
type JSDocSignature = function(number) : void;
//                    ^^^^^^^^^^^^^^^^^^^^^^^-JSDoc types can only be used inside
//                                            documentation comments. TS8020

Other than that the only significant difference between the two is that TypeScript syntax allows you to specify the name of the arguments.

If you hover over the two cb arguments of this playground link, you'll see that the JSDoc type gets converted to the Typescript type with the argument name set to arg0.

/**
 * @param {function(number) : void} cb
 */
function takesCallback1(cb) {}
//                      ^^
//                      (arg0: number) => void

/**
 * @param {(x: number) => void} cb
 */
function takesCallback2(cb) {}
//                      ^^
//                      (x: number) => void

So which one should you use? If you're generating docs using JSDoc.app, you should use the JSDoc type. If you're only concerned about IntelliSense getting things right, either will work, but the TypeScript syntax allows you to specify the argument name.

Upvotes: 3

Related Questions