How to access class type arguments within a static method in Typescript: A clever solution

An issue has arisen due to the code below

"Static members cannot reference class type parameters."

This problem originates from the following snippet of code

abstract class Resource<T> {
    /* static methods */
    public static list: T[] = [];
    public async static fetch(): Promise<T[]> {
        this.list = await service.get();
        return this.list;
    }
    /* instance methods */ 
    public save(): Promise<T> {
        return service.post(this);
    }
}

class Model extends Resource<Model> {
}

/* The desired outcome is as follows, but it's not permissible due to:
"Static members cannot reference class type parameters."
*/

const modelList = await Model.fetch() // inferred type would be Model[]
const availableInstances = Model.list // inferred type would be Model[]
const savedInstance = modelInstance.save() // inferred type would be Model

From this example, it can be inferred what I am aiming for. I wish to have the ability to call both instance and static methods on my inheriting class while having the inheriting class itself as the inferred type. To achieve this, I have found a workaround:

interface Instantiable<T> {
    new (...args: any[]): T;
}
interface ResourceType<T> extends Instantiable<T> {
    list<U extends Resource>(this: ResourceType<U>): U[];
    fetch<U extends Resource>(this: ResourceType<U>): Promise<U[]>;
}

const instanceLists: any = {} // an object that stores lists with constructor.name as key

abstract class Resource {
    /* static methods */
    public static list<T extends Resource>(this: ResourceType<T>): T[] {
        const constructorName = this.name;
        return instanceLists[constructorName] // using 'any' here, although effective :(
    }
    public async static fetch<T extends Resource>(this: ResourceType<T>): Promise<T[]> {
        const result = await service.get()
        store(result, instanceLists) // function that adds to instanceLists
        return result;
    }
    /* instance methods */ 
    public save(): Promise<this> {
        return service.post(this);
    }
}
class Model extends Resource {
}
/* now inferred types are correct */
const modelList = await Model.fetch() 
const availableInstances = Model.list 
const savedInstance = modelInstance.save()

The issue with this approach is that overriding static methods becomes cumbersome. For example:

class Model extends Resource {

    public async static fetch(): Promise<Model[]> {
        return super.fetch();
    } 
}

This will lead to an error because Model no longer correctly extends Resource due to the differing signature. There seems to be no straightforward way to declare a fetch method without errors or an intuitive mechanism for overloading.

The only working solution I could come up with is:

class Model extends Resource {
    public async static get(): Promise<Model[]> {
        return super.fetch({ url: 'custom-url?query=params' }) as Promise<Model[]>;
    }
}

In my opinion, this is not an elegant solution.

Is there a more efficient way to override the fetch method without resorting to manual casting to Model and complicated generic manipulations?

Answer №1

Here is a possible solution to your problem:

function Resource<T>() {
  abstract class Resource {
    /* static methods */
    public static list: T[] = [];
    public static async fetch(): Promise<T[]> {
      return null!;
    }
    /*  instance methods */
    public save(): Promise<T> {
      return null!
    }
  }
  return Resource;
}

In this code snippet, the Resource function is designed as a generic function that returns a locally declared class. The class returned by this function is not generic itself, so its static properties and methods have concrete types for T. You can extend it like this:

class Model extends Resource<Model>() {
  // overloading should also work
  public static async fetch(): Promise<Model[]> {
    return super.fetch();
  }
}

All the types are correctly inferred in this setup:

 Model.list; // Model[]
 Model.fetch(); // Promise<Model[]>
 new Model().save(); // Promise<Model>

This approach may work well for your needs. However, there are a couple of caveats to consider:

  • There is some repetition in

    class X extends Resource<X>()
    , which may not be ideal, but it seems necessary due to limitations in contextual typing.

  • Locally declared types are not typically exportable or used as declarations, so you might need to handle that carefully or find alternative solutions.

I hope this explanation helps you with your task. Best of luck!

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

styling multiple elements using javascript

Recently, I created a jQuery library for managing spacing (margin and padding). Now, I am looking to convert this library to pure JavaScript with your assistance :) Below is the JavaScript code snippet: // Useful Variables let dataAttr = "[data-m], [d ...

The JavaScript function modifies the value stored in the local storage

I'm in the process of developing a website that requires updating the value of my local storage when certain JavaScript functions are executed. Currently, I have this code snippet: localStorage.setItem('colorvar', '#EBDBC2'); I&ap ...

Include the particules.js library in an Angular 4 project

I am currently working on integrating Particles.js into my Angular project, but I am facing an issue with the Json file not loading. import { Component, OnInit } from '@angular/core'; import Typed from 'typed.js'; declare var particl ...

Acquiring the content of elements contained within a div container

On a webpage, I have included multiple div elements with unique IDs and the following structure: <div class="alert alert-info" id="1"> <p><b><span class="adName">Name</span></b><br> ...

Struggling with integrating Skybox in THREE.js

My console is not showing any errors. I am utilizing the live server VS code extension to execute the JS code. Can someone please assist me?" HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"& ...

Utilize Angular2 data binding to assign dynamic IDs

Here is the JavaScript code fragment: this.items = [ {name: 'Amsterdam1', id: '1'}, {name: 'Amsterdam2', id: '2'}, {name: 'Amsterdam3', id: '3'} ]; T ...

Guide on extracting a JavaScript string from a URL using Django

How can I extract "things" from the JavaScript URL "/people/things/" without any unnecessary characters? I've attempted inefficient methods like iteration, but struggle with removing the undesired parts of the string, leading to slow performance. Th ...

Is there a way to initiate a jquery function upon loading the page, while ensuring its continued user interaction?

On my webpage, there is a JavaScript function using jQuery that I want to automatically start when the page loads. At the same time, I want to ensure that users can still interact with this function. This particular function involves selecting a link tha ...

What is the best way to ensure that a child div can expand to fit within the scrollable area of its parent div

I am facing an issue with a parent div that changes size based on the content inside it. When the content exceeds the initial size, causing the parent to scroll instead of expanding, I have a child div set to 100% width and height of the parent. However, t ...

What is the best way to keep an image fixed at the bottom, but only when it's out of view in the section

There are two buttons (images with anchors) on the page: "Download from Google Play" and "Download from App Store". The request is to have them stick to the bottom, but once the footer is reached they should return to their original position. Here are two ...

Ways to include input values

In my form, there are 4 text boxes labeled as customer_phy_tot, customer_che_tot, and customer_bio_tot. I want to add up the values entered in these 3 boxes and display the sum in a 4th input box called customer_pcb_tot. customer_bio_obt.blur(function(){ ...

Using JavaScript to load the contents of a JSON file

I attempted to display data from a JSON file on an HTML page using jQuery / Javascript. However, each time I load the page, it remains blank. Below is the code snippet: index.html <!DOCTYPE html> <html> <head> <meta conten ...

Implementing Jsplumb in Angular 2

Struggling to integrate Jsplumb with Angular2. Attempting to incorporate jsPlumb into an Angular2 component, but encountering an error stating jsPlumb.ready is not a function Added it via npm and placed it in my vendor.js for webpack Below is the compon ...

Ways to substitute numerous instances of a string in javascript

I have experience in developing websites using reactjs. I usually implement restAPI's with java and work with liferay CMS. In one of my projects, I created a shortcode for accordion functionality like this: ('[accordion][acc-header]Heading 1[/ac ...

"Counting Down with PHP and jQuery : A Dynamic

I recently received a tutorial on how to combine PHP date function with jQuery. I am looking to modify the script so that when a specific time is reached, it redirects to another page. I attempted to make the changes myself but encountered some issues. Y ...

Choose a specific <div> element from an external page using Ajax/PHP

I'm encountering a small issue. I am currently utilizing Ajax to dynamically load content from another page into a <div> element after detecting a change in a <select>. However, my specific requirement is to only load a particular <div& ...

Tips for creating cascading dynamic attributes within Typescript?

I'm in the process of converting a JavaScript project to TypeScript and encountering difficulties with a certain section of my code that TypeScript is flagging as an issue. Within TypeScript, I aim to gather data in a dynamic object named licensesSta ...

Incorporate Angular directives within a tailor-made directive

I just started using a fantastic autocomplete directive called Almighty-Autocomplete. However, I feel like it's missing some features. The basic structure of the directive is as follows: .directive('autocomplete', function () { var index ...

Transfer groups between divisions

In my HTML structure, I have two main divs named Group1 and Group2. Each of these group divs contains at least two inner divs, all with the class .grp_item. Currently, the grp_item class is set to display:none, except for one div in each group that has a c ...

The rule 'react-hooks/exhaustive-deps' does not have a defined definition

I received an eslint error message after inserting // eslint-disable-next-line react-hooks/exhaustive-deps into my code. 8:14 error Rule 'react-hooks/exhaustive-deps' definition not found I tried to resolve this issue by referring to this p ...