Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

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

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Type check JavaScript files using JSDoc and Typescript 2.5

    Akash GuthaAkash Gutha

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

    typescriptTypeScript
    Code

    Code

    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
    Transcript

    Transcript

    00:00 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.

    00:25 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.

    00:38 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.

    00:52 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.

    01:06 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.

    01:15 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.

    Discuss

    Discuss