Typescript... or jsdocs ?

Typescript... or jsdocs ?

Each time I see an article (like this one) about typescript, they never quite seem to mention jsdocs. Therefore, it always feels like an unfair, one-sided comparison. Let's dive in some of the typical examples.

Type safety

This is probably the biggest argument... And while it's nice and convenient to be able to declare types directly, you can do something quite similar with jsdocs.

function add(a: number, b: number): number {
  return a + b;
}
/**
 * Add some numbers
 * @param {number} a
 * @param {number} b
 * @returns {number}
 */
function add(a, b){
  return a + b;
}

You might argue this adds quite a bit of boilerplate, but in most cases (something other than adding a and b) you would probably end up adding a docblock anyway to document the function usage, what the parameters actually do (not just their type...)... And best of all, with jsdocs, you could generate documentation from all this.

Detect errors

When jsdocs is used, you can detect errors statically in just about the same way. Just create your jsconfig.json.

{
  "compilerOptions": {
    "checkJs": true,
    "maxNodeModuleJsDepth": 1
  },
  "input": ["src"]
}

No need for typescript here...

Interfaces ?

interface Person {
  name: string;
  age: number;
}

const person: Person = {
  name: "Bob",
  age: 30
};

Is this really better than

/**
 * @typedef {Object} Person
 * @property {String} name
 * @property {Number} age
 */

/** @type {Person} */
const person= { name: 'Bob', age: 30 };

And again... what if you need to document some other things along the way ?

Conclusion

This is not to say that Typescript is bad. I'm sure it can help teams producing quality code. For my part, I don't like leaving up to some bundler to convert my code to something I don't control. I enjoy running native js code on the browser with no conversion whatsoever.

In any case, please stop saying that there is no way to type data in js without using typescript :-)