Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Unlock TypeScript's Features in Vanilla JS with @ts-check and JSDoc

    John LindquistJohn Lindquist

    TypeScript can help you with your plain JavaScript files if you add a simple //@ts-check comment. Then you can enhance the experience by add proper JSDocs to describe your functions which will feed type information into TypeScript and give you a development experience near TypeScript itself.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: If you create a random JavaScript file inside of a random folder, and just write some function -- we'll call this one greet as well, and just return one -- you can actually have TypeScript check this file by adding //@ts-check.

    Right now there's no errors, but we can see an error if we try something like greet and say hello. You'll see that greet says, "Expected zero arguments but got one." You could add the greeting in here to fix that.

    Where this gets really powerful is if you document your code with JSDoc. You do that with /** and VS Code will automatically generate an asterisk on each line as you hit return. I'll say @return then curlies string.

    This will say, "Type one, a number is not assignable to type string." Now, I'll have to return the greeting, and you'll see that error goes away. It's still saying that this greeting is of a type any, so let's go ahead and type that as well.

    We'll say @param, we'll say this is a string, and call this the greeting. This needs to be named. Then if I try and pass in a one here, you'll see one is not assignable to parameter type string, and also that my greetings, when I hover over them, get the information that it is a greeting.

    If I were to use this greet in a separate file, when I hovered over it, I would get all of that information, and the type information, even though my types are declared in JSDoc, and not inline inside my actual function.

    There are many more options than JSDoc. If you hit auto-complete you can see a long list of them. The more you document your JavaScript with JSDoc, the closer you can bring it to almost a native TypeScript experience.