Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio Code - type hints for JavaScript files

Is it possible to feed type information to the VS Code linter for JavaScript files? I have a JavaScript file and a .d.ts file and I'd like to have the JavaScript file parsed for type errors using this .d.ts file. Is that possible? If it's not possible directly in VS Code, is it possible using some other tool?

To add an example:

// file.d.ts
declare function f(x: number): number;

// file.js
function f(x) { return x * 2; }
f('Not a number'); // This should be an error
like image 606
Enn Michael Avatar asked Aug 29 '17 17:08

Enn Michael


People also ask

How do I beautify JavaScript in Visual Studio Code?

Just right-click on the text and select "Format code". Visual Studio Code uses js-beautify internally, but it lacks the ability to modify the style you wish to use. The extension "beautify" lets you add settings.

Is Visual Studio Code good for JavaScript?

VS Code ships with excellent support for JavaScript but you can additionally install debuggers, snippets, linters, and other JavaScript tools through extensions.


1 Answers

In general, you'll want to create a jsconfig.json file at the root of your project with the contents:

{
    "compilerOptions": {},
    "exclude": [
        "node_modules"
    ]
}

This file tells VS Code to treat all js files (and d.ts files) as part a the same project.

However it seems that TypeScript does not merge the type declaration of f in the d.ts file with the actual declaration of f in the js file. If you comment out the implementation, you get the correct type for f and the expected error:

// @ts-check

//function f(x) { return x * 2; }

f('Not a number'); // This is an error 

But otherwise, f has type function(x: any): number.

This seems unexpected to me and I've opened a new issue to track this: https://github.com/Microsoft/TypeScript/issues


Also, if you're only working in JavaScript, you can always use jsdoc comments to add type information:

// @ts-check

/**
 * @param {number} x 
 * @return {number}
 */
function f(x) { return x * 2; }

f('Not a number'); // This is an error 
like image 105
Matt Bierner Avatar answered Oct 16 '22 14:10

Matt Bierner