2

I have a JavaScript file that is being run with eval() by a VSCode extension. When the script is evaluated, its context already includes the global variable vscode (the VSCode API) which I am using from my script. All of that works fine.

What I want to know: Is there a way to use JSDoc annotations / TypeScript type definition files to tell VSCode that the vscode variable exists in the context?

I have tried this (I'm not sure if it makes any sense) and it didn't help:

// @ts-check
/// <reference path="node_modules/@types/vscode/index.d.ts" />

What does work is if I write:

const vscode = require('vscode')

But I'd rather not have to include that line because vscode already exists in the context.


UPDATE: More failed attempts

I tried creating a file types.d.ts:

export {}

declare global {

  var vscode: any
}

Referenced from the JS:

/// <reference path="types.d.ts" />

This works to satisfy the type checker of the existence of the global object, but I don't want vscode to be of type any. I want it to be the actual type of the vscode object. I don't know what that type is though. I can't find a type definition for it, only a module definition:

declare module 'vscode' {
     ...
}

Is that the type? How can I use it?

I've tried:

export {}
import vscode from 'vscode'

declare global {

  var vscode: vscode
}

But that fails on the import: "Module 'vscode' has no default export." or, if I put braces around the name, "Module 'vscode' has no exported member 'vscode'"

Any suggestions?


UPDATE: Success!

I've worked out how to do it. I needed to use typeof to get the type of the module.

export {}

declare global {

  var vscode: typeof import('vscode')
}

There's probably a way to do it more directly with JSDoc annotations in the JavaScript, but I want the types.d.ts file for other types anyway.

ᴇʟᴇvᴀтᴇ
  • 12,285
  • 4
  • 43
  • 66
  • Does this answer your question? [JSDoc is this how you mark a @typedef as @global?](https://stackoverflow.com/questions/46436950/jsdoc-is-this-how-you-mark-a-typedef-as-global) – Leon Oct 17 '21 at 14:01
  • I suspect it's something along those lines, but I don't know exactly what to write. 'vscode' is declared as a module and I don't know how to use a module as a type. I think I'm missing some important concepts. – ᴇʟᴇvᴀтᴇ Oct 17 '21 at 16:01
  • Hmm, I looked at vscode extension docs (https://code.visualstudio.com/api/get-started/your-first-extension#debugging-the-extension) and it seems that they import it as a module. Can this be applied to your case? – Leon Oct 17 '21 at 16:23
  • No, because I want to avoid using imports in my JS. But thanks for your suggestion because it helped me realise what I need to do. – ᴇʟᴇvᴀтᴇ Oct 17 '21 at 16:28

0 Answers0