Become a member
to unlock all features

Level Up!

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


    Type check JavaScript files using JSDoc and Typescript 2.5


    Typescript 2.5 adds JSDoc type assertion support for javascript file via ts-check service.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    We'll go ahead and make a function and call it strictlyNumbers. We'll pass in a number, and inside this, we'll log it. I call this function, passing in a string. If we go ahead and run that file in Node, we can see the JavaScript runs this function without throwing any errors.

    That is because JavaScript neither does type checking nor has an embedded type system. TypeScript augments this exact functionality by including JS doctype assertion support for JavaScript files inside the TS check service.

    Once we import the TS check service, we will be able to write JS doctype assertions in front of the parameters and enable type checking. We'll write a direct type, and in the curly braces, we'll pass it in the type number.

    We can quickly see that VS code throws an error on the function. There it says, "Argument of type 100 is not assignable to parameter of type number." You can see that we have enforced type checking in JavaScript.

    We can quickly fix this by changing this into a number. You can see that that error is gone. If we change this back into a string, the error is reproduced.

    View mode is a suggested service that TypeScript provides us to enforce type checking in JavaScript files, but this doesn't actually affect the compilation process. If we go ahead and run this in our terminal or Node, it will work perfectly fine.