DEV Community

Cover image for What is JSDoc and why you may not need typescript for your next project?
Cherry Ramatis
Cherry Ramatis

Posted on

What is JSDoc and why you may not need typescript for your next project?

It has been a couple of weeks since I started testing out this technology, JSDoc, for maintaining some JavaScript codebases. This has been especially important after some major events that occurred in the last few months.

Those events generated a lot of buzz through the tech community primarily with the argument that "removing typescript is the same as removing types" and that typescript is the only way to write safe javascript. In this article we'll discuss further what is JSDOC, what is the purpose of typescript and why you may not need typescript!

Table of contents

What is JSDOC anyway?

JSDOC is a predefined method of documenting code for javascript ecosystem created in 1999 that works similar to libraries for other languages such as: Javadoc for java, YARD for ruby, etc..

Practically speaking jsdoc is a way to write comments that the LSPs or any other tool can parse and provide information for the developer, basically a markup language (you know, like HTML) for coding samples, for example:

/**
 * The `foo` function append two strings and return the appended return.
 * @param {string} a
 * @param {string} b
 * @returns {string}
 * @throws {Error} If the first string is empty
*/
function foo(a, b) {
    // Code...
}
Enter fullscreen mode Exit fullscreen mode

That produces the following output using the tsserver LSP:

Output from tsserver using jsdoc

With that markup language, we can define text-related information such as function descriptions, error cases (throws), and language-specific details like type signatures for parameters and return values that populate TypeScript's own signatures, as you can see in the screenshot.

There is a lot of specific symbols presented on the JSDOC specification that can be found here: https://jsdoc.app

What is TypeScript?

Disclaimer: This article will not focus on the specific details about type level typescript, if your demand involves that level of type checking you're probably fine using typescript.

TypeScript is a linter and compiler/transpiler that provides a specific syntax for defining types and other specific language constructs such as interfaces, abstract classes, decorators, etc.

At the time it was created, TypeScript surely changed how everyone writes JavaScript. It not only introduced a new language but also competed with Babel in providing a way to support new language features without waiting for official ECMA support.

Besides the features TypeScript itself proposed, the most important thing it brought to the community was the ability to create cool features around this compiler that enhance the developer experience and productivity. Tools like tsserver, pretty ts errors, and many others are actively improving the ecosystem for both JavaScript and TypeScript writers.

Which problems typescript solves?

Most people think that typescript only brought type checking for our codebases, but it's not the only thing it shines:

  • Stop the run with ECMAScript Support: With TypeScript, we have the opportunity to use cutting-edge JavaScript features without worrying about browser support. Therefore, features like abstract classes, interfaces, and decorators become accessible to the developer.
  • Behold! The types are coming: Together with providing support for modern JavaScript features from the community, TypeScript also provides a Turing complete type system that allows both simple checking and complex type logic, mostly used by library authors.

It's important to point out that TypeScript really shines for library developers in the JavaScript ecosystem. If you want to provide a great experience for your users when installing your library, then TypeScript is probably the best solution for the case.

For those who want to improve their type level skills, I highly recommend this repository for learning by doing: https://github.com/type-challenges/type-challenges.

Another caveat is that TypeScript is not the only way to transpile JavaScript accessible for older versions. If you don't need specific features of TypeScript, it's possible to use alternatives that don't perform type checking.

Which problems JSDOC can solve by itself?

Since JSDoc is just a markup language built on top of javascript comments the solvable problems are very narrowed to that aspect, so it's mainly used for:

  • Documenting functions or classes.
  • Infering simple types for parameters, returns, class variables, etc..
  • Interacting with TypeScript complex type system via .d.ts files
  • Utilizing the potential of already existing tools like the TypeScript compiler and LSP.

Most people default to the TypeScript language as the only way to interact with the compiler and LSP. However, JavaScript using JSDoc is a perfectly fine way to maintain highly secure software without dealing with complex bundle times (if you want to bring a bundle, simply select one from the list presented in the previous topic).

How to type check code using TypeScript compiler in a Javascript + JSDOC codebase

Since TypeScript is just a linter and it has support for JSDOC types, we can even get the full power of tsc on our CI pipelines without worrying about bundling altogether.

First let's define a fairly complex type interacting with .d.ts file for extra TypeScript magic without bundling.

Setup a simple project with npm init -y and write the following index.js file:

/**
 * foo....
 * @param {import('./types.d.ts').ComplexType<number, { message: string }>} complexType
 * @returns {string}
*/
function foo(complexType) {
    if (complexType.type === 'err') {
        console.log(complexType.data.message)
        return
    }

    return complexType.data
}
Enter fullscreen mode Exit fullscreen mode

See how the import keyword is being used to import a type file? You can think of this approach as the .h and .c files from the C language.

Disclaimer: This JSDOC feature was implemented by the TypeScript team itself together with a lot more possibilities: https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html

Now to define the types.d.ts file, I tried to implement a fairly complex type simulating Result from Rust just to show that we can use full typescript potential with this method:

type Ok<T> = { type: 'success', data: T }
type Err<T> = { type: 'err', data: T }

export type ComplexType<V, E> = Ok<V> | Err<E>
Enter fullscreen mode Exit fullscreen mode

After defining our sample code, we can use the full power of the typescript linter without using it's compiler, let's define the following tsconfig.json config file for that:

{
    "compilerOptions": {
        "checkJs": true
    },
    "exclude": ["node_modules"]
}
Enter fullscreen mode Exit fullscreen mode

And we can finally run our command to check the entire code and see a type error (that I hope you already saw before 👀):

Type error from tsserver

Conclusion

This article was my exploration around the current news of big projects dropping TypeScript from their codebase while still maintaining type checking experience (only svelte) and I hope to have successfully shown my surprise of how much it's possible to achieve without using bundling by default.

I want to point out again that using TypeScript is not a problem at all, and that without this language we wouldn't get amazing projects such as the tsserver LSP.

May the force be with you! 🍒

Top comments (31)

Collapse
 
brense profile image
Rense Bakker

primarily with the argument that "removing typescript is the same as removing types"

That's not really true. Ignoring all the uninformed anti/pro trolls for a second. The main argument was: "why even???" And the main reasoning was: "muh compile time bruh" which is a dishonest argument, because you're not doing tsc at every hot reload, infact you only do it when building and then it takes all of 5 seconds for a million line project, which is really peanuts compared to the time it takes to run a bundler on the same project (yes I'm conveniently ignoring people who don't have any compile step in their project).

And the 2nd main reasoning was: "we are a community project and not everyone in the community knows typescript" which I could partially understand, if you don't follow it up with "let's use jsdoc for typing!" Which is really the same as tsconfig strict = false.

And if you don't use either then yes, you are removing all types and yes I'm strongly convinced that is bad.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Ignoring all the uninformed anti/pro trolls for a second.
[...]
and yes I'm strongly convinced that is bad.

It does come across as a bit dishonest to dismiss people mostly arguing from personal preference as uninformed trolls only to then go on to simply assert an opinion like that.

Maybe you can point out some actual trolls that I'm just not seeing in this discussion, but from what I see both here in this comment section and more widely the discussion around typescript is that most people simply prefer to code either with or without types.

It also seems a bit condescending to imply that the only reason someone might not prefer typescript is that they don't know typescript. Some people just don't like types, and that's okay.

Collapse
 
brense profile image
Rense Bakker

So basically you agree. It boils down to whether you think a type system is important or not. All other arguments that people use to hate on typescript are basically nonsense.

Thread Thread
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

No. It boils down to whether you think the value of a type system outweighs the problems it brings. Both are relevant questions; if you think the value it adds is low, smaller nitpicks will be what keeps you from using it. Pretending any of these problems are "nonsense" is little more than arrogance.

Arguments like "but it requires an extra build step" may not amount to much if you see immense value in a type system. But for someone to whom types aren't of much importance, that is a very good reason to just use plain JS.

It's like picking up an apple and finding a worm inside. If you're starving, you might think that's a dumb reason not to eat it. If you aren't hungry and don't even like apples, it's a very good reason to just throw it away and eat a donut instead.

Thread Thread
 
brense profile image
Rense Bakker

But it doesn't require an extra build step during development. There is no worm and donuts are bad for your health =p

Thread Thread
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Browsers running typescript directly is news to me

Thread Thread
 
brense profile image
Rense Bakker

Your dev server that serves your static files to the browser does. It's because of the fact that typescript is a superset of JavaScript, meaning, when you omit the types, its just JavaScript and your dev server can do that omission during transpilation, without extra overhead. Also if you did actually compile the typescript, it's also only compiling files that have actually changed and even if you compiled from scratch that typically only takes a few miliseconds as well. Minifying your JavaScript for production takes way longer.

Thread Thread
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

...so a build step then? I rest my case.

Thread Thread
 
brense profile image
Rense Bakker

No build step during development. I rest my case, you're deliberately trying to spin things to fit your own narrative, which is based on deep hatred, instead of actual arguments.

Thread Thread
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Honestly, I don't want to have a discussion with someone who gets this emotional over a programming language. Have a nice day.

Collapse
 
jmfayard profile image
Jean-Michel 🕵🏻‍♂️ Fayard • Edited

I feel grumpy that this is still an issue in 2024 whether and how to do types.
Static types are a foundational feature of not only modern programming, but also ancient programming. Great programming hero Tony Hoare invented them in 1965. Yes, you have read that right.

It is really unfortunate that the design of JavaScript was rushed in ten days in order to be ready for Netscape 1.0. The current mess where people argue over typescript and jsdoc and vanilla javascript all comes from trying to fix things after that unfortunate fact.

My real point is that types should be a "Don't Make Me Think" issue.

Collapse
 
cherryramatis profile image
Cherry Ramatis

Types are great, I love types, but Typescript trade-offs are not only having types vs not having types

Collapse
 
jmfayard profile image
Jean-Michel 🕵🏻‍♂️ Fayard • Edited

Yes you are right and I understand.
What I am saying that there should be no tradeoff.
It's a strange story without anyone being bad or wrong about anything.

I imagine a world where Netscape would have decided to wait a bit and polish JavaScript before releasing it for Netscape 1.0 and make upgrading it very difficult, so difficult that even the best can't do it right.
In this world, there would have not been drawbacks for Netscape because while JavaScript was pretty much useless at the time of Netscape 1.0. Gmail the first impressive Javascript app is from 2003, way after that.
JavaScript was useful only for marketing purpose at that time, but they got the marketing wrong, they called it Java something because Java was the hype new language of the internet.
Young recruiters wouldn't make the obvious rookie mistake of not thinking that two languages that have a very similar name have nothing to do with each other.

Netscape and Brendan Eich would have had time to polish its rough edges.
Douglas Crockford wouldn't have had to write "JavaScript the good parts" with his last chapters about bad and horrible parts that would mostly not exist.
Everyone else would not have had had to fight so much to fix one issue of JavaScript after another.
It's impressive the work that the JavaScript has done to overcome all of this, but this would not have been as necessary

And most importantly, countless developers would have had as first language the good parts of this language, but without the bad and awful part.
Right from the start, where it matters most from a pedagogical point of view, they would have had more developer sanity by design.

This word I imagine would have been slightly but meaningfully better

Thread Thread
 
lionelrowe profile image
lionel-rowe

But think about what we would have lost if JS was well-designed. I for one don't want to live in a world where "hello".fixed() didn't equal "<tt>hello</tt>"

Thread Thread
 
jmfayard profile image
Jean-Michel 🕵🏻‍♂️ Fayard

I didn't know that, that's super funny <3

Collapse
 
starboysharma profile image
Pankaj Sharma

🌟 Hey there! 🌟

I just want to share my experience with JSDoc 😉

I've started using JSDoc in our legacy project since I can't install TypeScript in my environment. The best part? No need for any third-party package installations! 🎉 Now, we're not just coding; we're also keeping our documentation game strong.

Happy coding everyone! 🚀👩‍💻👨‍💻

Collapse
 
cherryramatis profile image
Cherry Ramatis

Yeah me too, every time i need to maintain an old javascript codebase I just sprinkle a lot of jsdoc and be done with it

Collapse
 
endymion1818 profile image
Ben Read

Same here. In a team where I’m the only JavaScript engineer I have to support the rest of the team who are unfamiliar with a lot of new concepts in JS. JSDoc allows us to get the best of both worlds. Thanks for the article!

Collapse
 
suamirochadev profile image
Suami Rocha

the queen of articles <33

Collapse
 
kansoldev profile image
Yahaya Oyinkansola

I didn't know about JSDocs, it looks strange to me though, do i need to learn TypeScript in order to use it?

Collapse
 
cherryramatis profile image
Cherry Ramatis

No at all, jsdoc is just a comment pattern that you can use with or without typescript

Collapse
 
phenriquesousa profile image
Pedro Henrique

Thanks for sharing ❤️

Collapse
 
_ndeyefatoudiop profile image
Ndeye Fatou Diop

Great post ! I generally use Typescript and love it! I didn't know you could also use JSDocs this way. Do you also get helpful editor warnings when doing the wrong thing in the editor ?

Collapse
 
cherryramatis profile image
Cherry Ramatis

Yes! with the correct tsconfig (provided on the article) you can get all the feedback from tsserver

Collapse
 
clintonrocha98 profile image
Clinton Rocha

Ótimo artigo, será que depois desse artigo a comunidade js/ts vai começar a questionar o uso dessas ferramentas? Seria uma boa hhahahaha

Collapse
 
cherryramatis profile image
Cherry Ramatis

adoraria que começasse daskodasko

Collapse
 
spock123 profile image
Lars Rye Jeppesen

Typescript rocks. Stop being scared of static typings. The days of Perl script kiddies are over

Collapse
 
cherryramatis profile image
Cherry Ramatis

Typescript does rock, the point of the article is literally saying that you can use static typing from the typescript linter + LSP without actually buying the bundle part of the equation :D

Collapse
 
dnnnvx profile image
Marco

I don't understand people complaining about "third party tools", you just have to install typescript, also for the "compile time" there are tools (swc, ...) written in Rust that can compile everything in like... 2 seconds.

I think deciding for JSDoc is useful just for the "writing documentation without even realising it".

I'll try JSDoc at some point, but never had problems with TS since it solves lots of problems. The only thing is that it doesn't make sense in some frontend stuff, like in React, where types are kinda ugly and annoying - imho:

  • JSDoc => scripts / frontend / simple libraries (for docs)
  • Typescript => more complex projects / backend.
Collapse
 
masudalimrancasual profile image
Masud Al Imran

Yeah, no thanks. I will still use typescript on my next projects.

Collapse
 
cherryramatis profile image
Cherry Ramatis

alrighty

Some comments may only be visible to logged-in visitors. Sign in to view all comments.