We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Declaration Files

If you've ever seen funky looking .d.ts files and wondered what they are, they're declaration files. They only contain type information - no runtime code is allowed. They're very useful for defining the types for JavaScript code that exists in your app, but that doesn't have any type information.

For example, in Boot.dev we support login with Google. We use TypeScript in our codebase, but we just include Google's JavaScript library in our HTML as per their instructions. Because we want the static type hints in our editors, we have this global.d.ts file in our project:

declare global {
  interface Window {
    google: Google;
  }
}

interface Google {
  accounts: {
    id: {
      renderButton: (
        a: HTMLElement,
        b: {
          type?: string;
          theme?: string;
          size?: string;
          text?: string;
          shape?: string;
          width?: number;
        },
      ) => void;
      prompt: () => void;
      cancel: () => void;
      initialize: ({ client_id: string, callback }) => void;
      disableAutoSelect: () => void;
      revoke: (client_id: string, callback) => void;
    };
  };
}

export {};

It just says, "Hey, there's a global variable called google on the window object, and it has this shape." Now we can use window.google in our code and get type hints in our editor. It doesn't do anything for us at runtime, but it makes our lives much easier when writing the code.

Assignment

Support.ai started off as a vanilla JavaScript shop (ew), and not all legacy code has been ported over. Let's work around that.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Support.ai Dev Tool</title>
    <script type="module" src="./legacy.js"></script>
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <h1>Support.ai Dev Tool</h1>
    <button id="enable-button">Enable Auto-Reply</button>
  </body>
</html>
window.supportAI = {
  version: "0.1-alpha",
  enableAutoReply() {
    alert("Auto-reply enabled.");
  },
};
const button = document.getElementById("enable-button")!;

button.addEventListener("click", () => {
  window.supportAI.enableAutoReply();
});

TypeScript should now be complaining that supportAI doesn't exist on Window.

tsc
npx http-server .

You can also use bun serve, python3 -m http.server, or any local server you like.

Run and submit the CLI tests.

When debugging, if you make changes, be sure to recompile with tsc and hard refresh the browser page.