You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/languages/javascript.md
+45
Original file line number
Diff line number
Diff line change
@@ -206,6 +206,51 @@ This enables type checking for all JavaScript files in the project. You can use
206
206
207
207
JavaScript type checking requires TypeScript 2.3. If you are unsure what version of TypeScript is currently active in your workspace, simply run the **TypeScript: Select TypeScript Version** command to check.
208
208
209
+
### Global Variables and Type Checking
210
+
Let's say that you are working in legacy JavaScript code that uses global variables or non-standard DOM APIs:
211
+
212
+
```ts
213
+
window.onload=function() {
214
+
if (window.webkitNotifications.requestPermission() ===CAN_NOTIFY) {
If you try to use `// @ts-check` with the above code, you'll see a number of errors about the use of global variables:
223
+
224
+
1.`Line 2` - `Property 'webkitNotifications' does not exist on type 'Window'.`
225
+
2.`Line 2` - `Cannot find name 'CAN_NOTIFY'.`
226
+
3.`Line 3` - `Property 'webkitNotifications' does not exist on type 'Window'.`
227
+
228
+
If you want to continue using `// @ts-check` but are confident that these are not actual issues with your application, you have to let TypeScript know about these global variables. To start, [create a `jsconfig.json`](#_javascript-project-jsconfigjson) at the root of your project:
229
+
230
+
```json
231
+
{
232
+
"compilerOptions": { },
233
+
"exclude": [
234
+
"node_modules"
235
+
]
236
+
}
237
+
```
238
+
239
+
Then reload VS Code to make sure the change is applied. The presence of a `jsconfig.json` lets TypeScript know that your Javascript files are part of a larger project.
240
+
241
+
Now create a `globals.d.ts` file somewhere your workspace:
242
+
243
+
```ts
244
+
interfaceWindow {
245
+
webkitNotifications:any;
246
+
}
247
+
248
+
declarevar CAN_NOTIFY:number;
249
+
```
250
+
251
+
`d.ts` files are type declarations. In this case, `globals.d.ts` lets TypeScript know that a global `CAN_NOTIFY` exists and that a `webkitNotifications` property exists on `window`. You can read more about writing `d.ts`[here](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html). `d.ts` files do not change how JavaScript is evaluated, they are used only for providing better JavaScript language support.
252
+
253
+
209
254
## Linters
210
255
211
256
A [linter](https://en.wikipedia.org/wiki/Lint_%28software%29) is a tool that provides warnings for suspicious looking code. VS Code supports linters through [extensions](/docs/editor/extension-gallery.md). Linters provide warnings, errors, and light bulb actions.
0 commit comments