I have a Typescript/JavaScript hybrid project and I'm creating declaration d.ts
files for some of the JavaScript files in order to aid in the management of multiple classes and subclasses.
However the declared types are not being seen by Visual Studio Code. I have the js
and corresponding d.ts
files in the same directory.
For example:
my-class.js
class MyClass {
constructor(options) {}
action(num) {
return num.toString()
}
}
}
my-class.d.ts
export interface Options {
a: boolean
b: boolean
}
export declare abstract class MyClass {
constructor(options: Options)
action(num: number): string
}
IntelliSense does not pick up the definitions, for instance, when I hover over the action
method of my-class.js
.
I've tried adding a reference annotation at the top of my-class.js
with no effect (///<reference path="./my-class.d.ts" />
).
I have the checkJs
option set to true
in my settings.
I'm using VS Code Version 1.19.1
Are there other actions I need to take in order for this to work?
Make sure you have a jsconfig.json file in your working folder. After you have this config file your .d.ts files should be included/reference.
Regarding your specific example, as far as I know, it's not going to work as you expect. This is because of declaration scope. Meaning, in your .d.ts file you define a MyClass with TypeScript types, then in your .js file you define a second MyClass, this second declaration also has types, it has default types of any. If you were inheriting from the first class then it may work as your expecting.
That being said there are things that will work:
Example:
my-class.d.ts
declare interface Options {
a: boolean
b: boolean
}
declare class MyClass {
constructor(options: Options)
action(num: number): string
}
my-class.js
class MyClass {
/**
* @param {Options} options
*/
constructor(options) {
}
action(num) {
return num.toString();
}
}
var foo = new MyClass({ a: true, b: false } );
foo.action(88);
If you hover over the foo instance in the .js file you will notice that you do get correct IntelliSense
By adding the JSDoc Comment "@param {Options} options" to the constructor() you will also get correct IntelliSense
JSDoc and TypeScript: https://github.com/Microsoft/TypeScript/wiki/JsDoc-support-in-JavaScript VSCode and TypeChecking: https://code.visualstudio.com/docs/languages/javascript#_global-variables-and-type-checking
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