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
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.
VS Code ships with excellent support for JavaScript but you can additionally install debuggers, snippets, linters, and other JavaScript tools through extensions.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With