Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference same class

class MyClass{

  someMethod(): MyClass{
     return new MyClass();
  }

}

How to reference current class, without explicitly passing the name?

Something like this:

class MyClass{

  someMethod(): self{
     return new self();
  }

}

Obviously that doesn't work, but you get the idea.

like image 702
Alex Avatar asked Oct 26 '25 06:10

Alex


2 Answers

TypeScript will not recognize this.constructor as callable. Use Object.getPrototypeOf(this).constructor to get a reference to it instead.

This is the most straightforward way of doing this with strict type safety:

class SelfReference {
    /**
     * Assign some constructor arguments to the instance for testing.
     */
    constructor(private a: number, private b: number) {}

    /**
     * Create a new instance of `Object.prototypeOf(this).constructor`.
     */
    newInstance(...args: ConstructorParameters<typeof SelfReference>) {
        const { constructor } = Object.getPrototypeOf(this);
        return new constructor(...args);
    }
}

const firstReference = new SelfReference(1, 2);
const newReference = firstReference.newInstance(3, 4);

console.log({ firstReference, newReference });

Logs:

[LOG]: {
  "firstReference": {
    "a": 1,
    "b": 2
  },
  "newReference": {
    "a": 3,
    "b": 4
  }
} 

I would not recommend doing this though, it's a pretty ugly anti-pattern.

TypeScript Playground

like image 185
C. Lewis Avatar answered Oct 28 '25 21:10

C. Lewis


This can be accomplished by using getPrototypeOf:

Class myclass {

  constructor() {}
  class(): this {
    const ctor = Object.getPrototypeOf(this).constructor;
    return new ctor();
  }
}

Using the ctor(), we are not calling myclass specifically!

Mozilla - Globa_Objects/Object/getPrototypeOf

like image 23
DialFrost Avatar answered Oct 28 '25 21:10

DialFrost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!