Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

I've write the following decorator in TS but compiler throws an error pointing to class…

  1. User

    I've write the following decorator in TS but compiler throws an error pointing to class keyword in the line return class extends originalConstructor {. I bring the error text right bellow the code. Please explain what exactly it says because I can't understand it.

    function WithTemplate(template: string, hookId: string) {
      console.log('TEMPLATE FACTORY')
      return function <T extends new (...args: any[]) => T>(
        originalConstructor: T
      ) {
        return class extends originalConstructor {
          constructor(...args: any[]) {
            super(args)
            console.log('Rendering template')
            const hookEl = document.getElementById(hookId)
            if (hookEl) {
              hookEl.innerHTML = template
              hookEl.querySelector('h1')!.textContent = this.name
            }
          }
        }
      }
    }
    

    "Class '(Anonymous class)' incorrectly extends base class 'T'. '(Anonymous class)' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'new (...args: any[]) => T'.ts(2415)"

  2. Assistant

    The error message you're encountering is due to how you've defined the generic type parameter T in your decorator. Let's break down the error and understand what's going on.

    Your Original Code:

    function WithTemplate(template: string, hookId: string) {
      console.log('TEMPLATE FACTORY')
      return function <T extends new (...args: any[]) => T>(
        originalConstructor: T
      ) {
        return class extends originalConstructor {
          constructor(...args: any[]) {
            super(args)
            // ...
          }
        }
      }
    }
    

    The Error Message:

    Class '(Anonymous class)' incorrectly extends base class 'T'.  
    '(Anonymous class)' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'new (...args: any[]) => T'.ts(2415)
    

    Explanation:

    1. Circular and Incorrect Type Definition:

      The type parameter T is defined as:

      T extends new (...args: any[]) => T
      

      This means that T is a constructor function that, when called with new, returns an instance of T itself. This is recursive and circular because T is being defined in terms of itself, which confuses the TypeScript compiler.

    2. TypeScript's Concern:

      The compiler is concerned that while your anonymous class (the one you're returning from your decorator) is assignable to T, T could also be instantiated with a different subtype. This means that the base class T might not be correctly extended by your anonymous class in all cases, leading to potential type safety issues.

    3. Incorrect super Call:

      In your constructor, you have:

      super(args)
      

      Since args is an array of arguments, you should spread it when calling super:

      super(...args)
      
    4. Accessing 'this.name':

      You're accessing this.name in your code. For TypeScript to understand that this has a name property, you need to ensure that the base class's instance type includes a name property.

    How to Fix It:

    1. Correct the Type Definition of T:

      Instead of defining T in terms of itself, define it as a constructor that returns an object (or an object with specific properties if needed).

      T extends new (...args: any[]) => {}
      

      Or, if you need to access this.name, specify:

      T extends new (...args: any[]) => { name: string }
      
    2. Fix the super Call:

      Spread the args array when calling super:

      super(...args)
      
    3. Rewriting the Decorator:

      Here's the corrected version of your decorator:

      function WithTemplate(template: string, hookId: string) {
        console.log('TEMPLATE FACTORY')
        return function <T extends { new (...args: any[]): { name: string } }>(
          originalConstructor: T
        ) {
          return class extends originalConstructor {
            constructor(...args: any[]) {
              super(...args)
              console.log('Rendering template')
              const hookEl = document.getElementById(hookId)
              if (hookEl) {
                hookEl.innerHTML = template
                hookEl.querySelector('h1')!.textContent = this.name
              }
            }
          }
        }
      }
      

    Summary:

    • The error occurs because the type parameter T is defined recursively, which confuses the compiler.
    • By providing a correct constraint for T, we inform TypeScript about the shape of the classes our decorator works with.
    • By fixing the super call and ensuring this has the correct type, we align our code with TypeScript's type system, resolving the error.

    Final Note:

    TypeScript's type system aims to ensure type safety. When defining generic types and class extensions, it's crucial to provide clear and non-circular type definitions so that the compiler can accurately check types and prevent potential runtime errors.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.