Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript class not picking up TypeScript declaration file in Visual Studio Code

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.

enter image description here

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?

like image 547
t.888 Avatar asked Jan 04 '18 16:01

t.888


1 Answers

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.

enter image description here

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:

  • You should get IntelliSense on the Instance of the class
  • You can add JSDoc comments to your .js files to define/link the .d.ts types

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

enter image description here

By adding the JSDoc Comment "@param {Options} options" to the constructor() you will also get correct IntelliSense

enter image description here

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

like image 70
Justin Avatar answered Oct 12 '22 06:10

Justin