-1

I have a script in my html file as this

              <script>
            if (window.TamaraProductWidget) {
      
              window.TamaraProductWidget.render();
            }
          </script>

I did this in my ts class to import the script src

      this.myScriptElement = document.createElement("script");
  this.myScriptElement.src = "https://.....-widget.min.js";
  document.body.appendChild(this.myScriptElement);

How do I call it in my typescript class? Since it's not working, but if I call window.TamaraProductWidget.render(); in console of browser it works well.

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Malakmkd
  • 121
  • 3
  • 14
  • 1
    How did you import the script file? You need it above your ` – Kaung Myat Lwin Aug 11 '22 at 13:44
  • 1
    You need ambient declarations so TypeScript knows the shape of `TamaraProductWidget` and that it's available in the global object – Ruan Mendes Aug 11 '22 at 13:50
  • Make sure to import that widget script before that inline script is run. – lupz Aug 11 '22 at 13:53
  • What do you mean by "it's not working"? That's a sentence you should avoid, we know you're here because something is not working. Instead, explain how it isn't working. Do you have a TypeScript error? A runtime error? – Ruan Mendes Aug 11 '22 at 13:56
  • Whoever closed this question as a dupe should be more careful. The question is about TypeScript, now about how to load a script dynamically. Notice they are able to call `window.TamaraProductWidget.render();` from the console without a problem. – Ruan Mendes Aug 11 '22 at 14:23

1 Answers1

2

It does not look like TamaraProductWidget provides TypeScript definitions. The best you can do is tell TypeScript that it's available globally as any.

// This does not create a var statement, 
// it just tells TS that the object is available globally
declare var TamaraProductWidget: any;
// No TypeScript errors
window.TamaraProductWidget.render();

See example on the TypeScript Playground

I recommend you ask the TamaraProductWidget team to provide TS definitions.

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217