Expanding the global object in ES6 modules to include TypeScript support for extensions like `Autodesk.Viewing.Extension`

I created a custom forge extension and now I am looking to incorporate typescript support as outlined in this blog post. However, I am facing an issue where typescript cannot locate the objects like Autodesk.Viewing.Extension and Autodesk.Viewing.ToolInterface because they do not exist during transpile time. To work around this, I have implemented a solution where I pass the parameter Autodesk through a factory function when creating the Extension class (see code example) due to the inability to access the global Autodesk variable from within an ES6 module. This workaround results in losing all type information.

Is there a way to fully integrate typescript into my custom extension?

My current workaround:

function(Autodesk: any) { // injects Autodesk by passing the global accessible Autodesk object...
        return class MyExtension extends Autodesk.Viewing.Extension {
            ...
        };
    }
    

Desired outcome (with typescript support):

class MyAwesomeExtension extends Autodesk.Viewing.Extension {
        constructor(viewer, options) {
            super(viewer, options);
        }

        load() {
            console.log('MyAwesomeExtensions has been loaded');
            viewer.setEnvMapBackground(null); // Hide background environment if there is one
            viewer.setBackgroundColor(0, 64, 128); // Set background color
            return true;
        }

        unload() {
            console.log('MyAwesomeExtensions has been unloaded');
            return true;
        }
    }

    Autodesk.Viewing.theExtensionManager.registerExtension('MyAwesomeExtension', MyAwesomeExtension);
    

Answer №1

One issue I faced was accessing global libraries from an ES6 module. However, a solution is using globalThis to access global variables within an ES6 module. This allows you to utilize typings as usual.

Take a look at this code snippet:

const Autodesk = globalThis.Autodesk;
const THREE = globalThis.THREE;

export class MyExtension extends Autodesk.Viewing.Extension {
   //...
}

The usage of the first two lines (e.g. const THREE = globalThis.THREE) can be avoided by configuring typescript to permit umd access:

{ 
  "compilerOptions": {
      "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to preserve an enumeration value in TypeScript?

Is there a way to save enumeration values in TypeScript? For instance: createArticle(name: string, clr: ??enumeration??) { return axios.post(`${environment.apiUrl}/cards`, { card: `${name}`, color: ??clr?? }, ... } PS: Conte ...

Having trouble utilizing Vue3 methods while utilizing the `<script setup lang="ts">` syntax

Looking to incorporate Vue into a non-Vue Class using the Composition API for a Chrome Extension project where having the entire thing as a Vue App doesn't make sense. The Vue Instance is being instantiated in the usual manner and then injected into ...

The enigma of TypeScript

Whenever I try to declare or initialize data members in a class, the following methods never seem to work: var view: string[]; var view: string[] = []; let view: string[]; let view: string[] = []; Even though the TypeScript documentation states that it s ...

When transitioning to generics, the narrowing of types in TypeScript is sometimes lost

I am intrigued by this scenario where Test1 fails while Test2 succeeds. I wonder if there is a way to have Test1 pass without altering the generic signature: enum TableType { Shipment = "Shipment", Batch = "Batch", } type Test& ...

Discovering the RootState type dynamically within redux toolkit using the makeStore function

I am currently working on obtaining the type of my redux store to define the RootState type. Previously, I was just creating and exporting a store instance following the instructions in the redux toolkit documentation without encountering any issues. Howev ...

What steps should I take to verify the validity of an Angular form?

I am struggling with validating an inscription form in HTML. Despite trying to implement validations, the inputs are still being saved in the database even when they are empty. Here are the validations I want to include: All inputs are required Email addr ...

What could be causing my function to not provide the expected output?

Whenever I try to invoke the function from another part of the code, I encounter an issue where it returns undefined before actually executing the function. The function is stored in a service. login.page.ts: ngOnInit(){ console.log(this.auth.getRole()) ...

Implementing pagination within an Angular 11 Mat-table with grouping feature

Encountering an interesting issue with MatTable pagination and grouping simultaneously. I have two components each with a Mat-table featuring Pagination+Grouping. ComponentOne functions smoothly without any issues. When choosing to display 5 elements pe ...

What is the reason behind being able to assign unidentified properties to a literal object in TypeScript?

type ExpectedType = Array<{ name: number, gender?: string }> function go1(p: ExpectedType) { } function f() { const a = [{name: 1, age: 2}] go1(a) // no error shown go1([{name: 1, age: 2}]) // error displayed ...

A function's behavior will vary depending on whether it is a property of an object or not

I've been observing some peculiar behavior: In a typical scenario, TypeScript usually raises an error when an object contains too many keys, like this: type Foo = { a: string; } const a: Foo = { a: "hello", b: "foo" // Ob ...

Learn the process of sending a delete request to a REST API with Angular

Is there a way to effectively send a delete request to a REST API using Angular? I am attempting to send a delete request with an ID of 1 My current approach is as follows: this.http.delete(environment.apiUrl+"id="+1).subscribe(data => { }); The va ...

Extending Error object disrupts `instanceof` validation in TypeScript

Could someone clarify why the error instanceof CustomError part of the code below returns false? class CustomError extends Error {} const error = new CustomError(); console.log(error instanceof Error); // true console.log(error instanceof CustomError); ...

Issue with conflicting namespaces warning when compiling an Angular 9 project with ng-packagr using Typescript

I'm trying to pinpoint the root cause of this problem, and I suspect it may be related to Typescript. However, it could also involve ng-packagr or Angular. This issue only arose after upgrading to Angular 9. Upon building my production environment, I ...

Issue found in VS2015 with the sequence of AngularJS TypeScript ts files within the appBundle.js file

I've been diving into AngularJS and TypeScript with the VS2015 RC Cordova TypeScript project. Recently, I created a "MyController.ts" file in the same folder as "index.ts". The code worked perfectly fine: module MyTestApp{ export class MyContro ...

Conditions are in an angular type provider with AOT

I am facing an issue with my Angular project that is compiled using AOT. I am trying to dynamically register a ClassProvider based on certain configurations. The simplified code snippet I am currently using is below: const isMock = Math.random() > 0.5; ...

Is there a way to halt the current traversal of visitEachChild in TypeScript Transformer API?

While navigating through each child node of a parent node using visitEachChild, is there a way to stop the process when I no longer wish to visit the subsequent child nodes? For example: Parent node Node 1 Node 2 <-- My target point. Node 3 Node 4 Nod ...

Angular2 - how can I effectively organize the logic between my components and services?

Within my current project setup, I have the following structure implemented: I have a Component that interacts with a Service Class which in turn calls an external API. The specific logic that I need to implement is related solely to the user interface. ...

WebStorm provides alerts for objects, types, and directives within Angular, yet they function properly

Why is WebStorm displaying warnings for objects, types, and directives in Angular Template HTML even though they are functioning correctly? Despite the fact that all types and Angular directives in the HTML structure are working fine within Angular on Web ...

Tips for handling catch errors in fetch POST requests in React Native

I am facing an issue with handling errors when making a POST request in React Native. I understand that there is a catch block for network connection errors, but how can I handle errors received from the response when the username or password is incorrec ...

Avoid triggering onClick events on all rows when clicking, aim for only one row to be affected per click

I have a unique situation where I have a table containing rows with a button in each row. When this button is clicked, it triggers an onClick event that adds two additional buttons below the clicked button. The Issue: When I click on a button, the onClick ...