B
B
bakunovdo2020-05-16 15:21:44
JavaScript
bakunovdo, 2020-05-16 15:21:44

VS Code in autocomplete doesn't display methods and functions from lib.dom for this...?

Can this be fixed somehow? Or maybe it just doesn't work in vscode. For example, everything is perfectly displayed in ide WebStorm, but it is not comfortable for me to work in it.

export class Page {
  constructor(selector, options) {

    //Автодополнений нет
    this.$element = document.querySelector(selector)
    this.$element. // <--
    
    //А в этом случае у меня есть автодополнения из lib.dom, тк указал явно
    const cnt = document.querySelector('.container')
    cnt. // <--
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2020-05-16
@bakunovdo

The main thing to understand is that out of the box in VSCode, hints in JS are based on TypeScript, they can be extended with plugins, but the basics will still remain exactly the same.
Since there are no static types in JS, VSCode tries to infer the type using TypeScript, but TypeScript is far from perfect.
In the case, the type can be deduced unambiguously - this is the Element type, and all because TS knows that the value in const will definitely not change and simply takes the return type for document.querySelector and displays hints for it. In the case of this.$element , the value can change, including somewhere outside, and JS completely allows you to change it to anything, so the any type is displayed, for which there are no hints.const cnt = document.querySelector('.container')
I will not agitate you to switch to TypeScript, as well as describe how much it saves time when developing something more complicated than 10-20 lines of code. I'll just suggest that TS in VSCode can also be enabled for regular JS files, even without tsconfig.json, just add a comment // @ts-checkto the beginning of the file, and you will immediately get more hints and some type control. I will also add that in js files you can annotate types through jsdoc:

// @ts-check
export class Page {
    constructor(selector, options) {
        /** @type Element */    
        this.$element = document.querySelector(selector)
        this.$element // тут работают подсказки после точки для типа Element
    }
}

D
Denis Ineshin, 2020-05-16
@IonDen

WebStorm is an IDE
VS Code is a text editor (the way is beautiful
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question