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.
Instructor: [00:00] 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.
[00:18] 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.
[00:35] 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.
[00:51] 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.
[01:07] 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.
[01:29] 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.
[01:45] 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.
You'll want to make sure that
javascript.validate.enable
is enabled in your VS Code settings in order to see type errors in your vanilla JS files.