Utilizing the power of dojo/text! directly within a TypeScript class

I have encountered examples suggesting the possibility of achieving this, but my attempts have been unsuccessful. Working with Typescript 2.7.2 in our project where numerous extensions of dijit._Widget and dijit._TemplatedMixin are written in JavaScript, we are transitioning towards Typescript gradually. I have defined an interface that extends these two classes (along with others) with a constructor in a d.ts file. This interface is then extended in a class implemented in Typescript using AMD class definition syntax. I am declaring an extension of this class and attempting to utilize dojo/text! to load an HTML template within the extension. The content of form.d.ts is as follows:

/// <reference path="../../../../../../../node_modules/dojo-typings/dojo/1.11/dojo.d.ts" />
/// <reference path="../../../../../../../node_modules/dojo- typings/dijit/1.11/dijit.d.ts" />
/// <reference path="../../../../../../../node_modules/@types/dom.generated.d.ts" />

declare namespace com {
  namespace foo {
    namespace bar {
      namespace web {
        namespace components {
          namespace form {
            interface ModelObjectMainFormView extends dijit._Widget, dijit._TemplatedMixin, dijit._WidgetsInTemplateMixin, dojo.Evented {
              on(type: string | dojo.ExtensionEvent, func: dojo.EventListener | Function): dojo.WatchHandle;
              emit(type: string | dojo.ExtensionEvent, ...events: any[]): boolean;
            }

            interface ModelObjectFormViewConstructor {
              new (args: Array<any>);
            }

          }
        }
      }
    }
  }
}

Contained in modules.d.ts:

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

declare module 'com/foo/bar/web/components/form/ModelObjectMainFormView' {
  type ModelObjectMainFormView = com.foo.bar.web.components.form.ModelObjectMainFormView;
  const ModelObjectMainFormView: com.foo.bar.web.components.form.ModelObjectFormViewConstructor;
  export = ModelObjectMainFormView;
}

declare module "dojo/text!*" {
  var _: string;
  export default _;
}

The AMD declaration for the extension reads as:

import declare = require("dojo/_base/declare");
import ModelObjectMainFormView = require("com/foo/bar/web/components/form/ModelObjectMainFormView");

class TSModelObjectMainFormView {
  inherited: (args: Object) => any;
}

var exp = declare("com.foo.bar.web.components.form.TSModelObjectMainFormView", [ModelObjectMainFormView], new TSModelObjectMainFormView());
export = exp;

Including the attempt at using dojo/text! in the extension code snippet below:

/// <amd-dependency path="dojo/text!com/foo/bar/web/workItems/configuration/forms/templates/ConfigurationWorkItemMainFormView.html" name="template" />
import * as aspect from 'dojo/aspect';
import * as domAttr from 'dojo/dom-attr';
import * as domClass from 'dojo/dom-class';
import * as domConstruct from 'dojo/dom-construct';
import * as lang from 'dojo/_base/lang';
import ModernizationUtil = require('com/foo/bar/rtc/web/util/ModernizationUtil');
import MimeTypes = require('com/foo/bar/web/scm/MimeTypes');
import * as TSModelObjectMainFormView from '../../../components/form/TSModelObjectMainFormView';
// import * as template from "dojo/text!com/foo/bar/web/workItems/configuration/forms/templates/ConfigurationWorkItemMainFormView.html";
let template: string;

export class ConfigurationWorkItemMainFormView extends TSModelObjectMainFormView {
  templateString = template;

  constructor(args?: any) {
    super(args);
  }
}

The use of amd-dependency comes into play due to the failure of importing dojo/text! during runtime when seeking the module, resulting in a "module not found" error. By using amd-dependency, template is explicitly defined as a string within the source, containing the HTML loaded by dojo/text!. The challenge arises because the call to super() in the constructor must precede other lines of code, yet it relies on templateString being set. However, the assignment of templateString occurs after the constructor's return.

Any insights or assistance would be greatly appreciated. Additional information can be provided upon request. Thank you for your help.

Answer №1

After some tinkering, I was able to successfully implement the changes needed for this to function properly: When modifying the AMD declaration of the extension:

class TSModelObjectMainFormView {
  templateString: string;
  inherited: (args: Object) => any;

  constructor(args?: any) {
    if (args && args.templateString) {
      this.templateString = args.templateString;
      this.inherited(arguments);
    }
  }
}

As well as adjusting the Typescript class that extends TSModelObjectMainFormView:

constructor(args: any) {
  super(lang.mixin(args, {templateString: template}));
}

I believe there may be a more efficient way to approach this. Any guidance or advice would be greatly appreciated. It appears that the current implementation still relies on amd-dependency, which is considered deprecated.

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 correct method for importing React in TypeScript (.tsx) to ensure optimal integration?

Within our TSX/React web application, we employ two distinct import styles for the react module: import * as React from "react"; as well as import React from "react" As far as I know, both methods function without any noticeable differences. Is there a ...

Updating and Preserving Content in Angular

I've encountered an issue while working on a code that allows users to edit and save a paragraph on the screen. Currently, the editing functionality is working fine and the save() operation is successful. However, after saving, the edited paragraph do ...

Using Typescript to assign a custom object to any object is a powerful feature

I am attempting to organize table data by utilizing the code found at https://github.com/chuvikovd/multi-column-sort. However, I am unsure of how to pass a custom object to the SortArray[T] object. The structure of my custom object is as follows: const ob ...

React Typescript Context state isn't refreshing properly

Struggling to modify my context state, I feel like I'm overlooking something as I've worked with context in the past. The challenge lies in changing the 'isOpen' property within the context. You can view my code here: CodeSand **app.ts ...

Having trouble launching React application on local machine due to missing node modules

I am completely new to React. I recently forked a project on Github and am attempting to run it on my own machine. However, I've noticed that the folder structure is missing the node modules. Does this mean I need to install create-react-app globally ...

Avoid generating `.d.ts` definition files during the onstorybook build process in a Vite React library project

I am currently developing a component library using react and typescript. I have integrated Vite into my workflow, and every time I build Storybook, the dts plugin is triggered. This has two undesired effects: It generates numerous unnecessary folders an ...

Why bother specifying types when extending tsconfig?

Having an angular app that utilizes @types and custom typings, I am facing an issue where the app works when served but encounters errors during testing with ng test. It is puzzling to me why this discrepancy exists, and I am struggling to comprehend the r ...

Dealing with client-side exceptions in a Next.js 13 application's directory error handling

After carefully following the provided instructions on error handling in the Routing: Error Handling documentation, I have successfully implemented both error.tsx and global-error.tsx components in nested routes as well as the root app directory. However, ...

NGXS: Issue with passing objects to "setState" occurs when any of the patched inner fields is nullable or undefined

In my Angular components, I have created a class that is responsible for storing the state: export class MyStateModel { subState1: SubStateModel1; substate2: SubStateModel2; } This class has simple subclasses: export class SubStateModel1 { someField ...

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...

Display JSON data in a table format using Angular

I have received a JSON result that looks like this: { "discipline":"ACLS", "course": [ { "value":"ACLS Initial", "classes":"0", "students":"0" }, { "BLS":"CPR Inst ...

Is Angular's ngOnChanges failing to detect any changes?

Within one component, I have a dropdown list. Whenever the value of the dropdown changes, I am attempting to detect this change in value in another component. However, I am encountering an unusual issue. Sometimes, changing the dropdown value triggers the ...

There seems to be an issue with calling this particular expression. The elements within the type 'string | ((searchTerm: string) => Promise<void>) | []' are not all callable

Here is my unique useResults custom hook: import { useEffect, useState } from 'react'; import yelp from '../api/yelp'; export default () => { const [results, setResults] = useState([]); const [errorMessage, setErrorMessage] = us ...

arrange items based on their category into arrays

I have a JSON file that needs to be arranged based on three specific fields. Here is an example snippet of the JSON data: { "Racename": "10KM", "Category": 34, "Gender": "Male", "Work": "Google", "FullName": "Dave Happner", "Rank": 1, "Poni ...

Angular input material with a stylish twist

How can I style all inputs on the Angular Material input component (matInput) using Typescript? I attempted to implement this solution, but it only affects the first element. ngAfterViewInit () { const matlabel = this.elRef.nativeElement.querySelecto ...

Steps for updating the value of a button in Typescript and React

I currently have a button that manages my language switcher, configured to handle cookies, URL changes, and now I want it to update the translations on the page as well. The <img> tag is utilized for changing the country flag. < ...

What is the best way to show TypeScript code using "<code>" tags within an Angular application?

I am looking to showcase some TypeScript (angular code) as plain text on my website using prismjs. However, the Angular framework is executing the code instead. How can I prevent it from running? I have attempted enclosing it within pre and code tags wit ...

Is there a user-friendly interface in Typescript for basic dictionaries?

I'm not inquiring about the implementation of a dictionary in Typescript; rather, I'm curious: "Does Typescript provide predefined interfaces for common dictionary scenarios?" For instance: In my project, I require a dictionary with elements of ...

Converting a string to the Date class type in Angular 4: A comprehensive guide

Within my .ts file, I have a string that looks like this: const date = "5/03/2018"; I am looking to convert it into the default date format returned by Angular's Date class: Tue Apr 03 2018 20:20:12 GMT+0530 (India Standard Time) I attempted to do ...

What is the best way to apply DateRange filtering in a Kendo Ui Grid?

Currently I am working with the Kendo Ui Grid and attempting to implement filtering by DateRange. Here is a snippet of my current code: HTML: <kendo-grid-column field="createdate" title="Creation Date" width="150"> <ng-template kendoGridFilterC ...