Sobes.tech
Middle

How can we describe a class in TypeScript that we create inside a function and return outside?

sobes.tech AI

Answer from AI

// Define type for class instance
type MyClassInstance = {
  myProperty: string;
  myMethod(): void;
};

// Type for class constructor
type MyClassConstructor = new () => MyClassInstance;

// Function that creates and returns a class
function createAndReturnClass(): MyClassConstructor {
  // Create an anonymous class here
  return class {
    myProperty: string = "Hello from class";

    myMethod() {
      console.log(this.myProperty);
    }
  };
}

// Get class from function
const DynamicClass = createAndReturnClass();

// Create an instance of the dynamic class
const instance: MyClassInstance = new DynamicClass();

// Use the instance
instance.myMethod();