javascript / expert
Snippet
Enforcing Abstract Class Contracts using new.target Metaprogramming
JavaScript does not have an explicit abstract keyword natively. However, abstract classes and interface constraints can be constructed using new.target inside the base constructor. new.target references the constructor function that was directly invoked by new, allowing abstract parent classes to prevent direct instantiation and enforce required method implementations on child classes.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class AbstractRepository {constructor() {if (new.target === AbstractRepository) {throw new TypeError('Cannot instantiate abstract class directly.');}if (typeof this.find !== 'function') {throw new TypeError(`${new.target.name} must implement method 'find()'.`);}}}class UserRepository extends AbstractRepository {find(id) {return { id, name: 'Alex' };}}const repo = new UserRepository();console.log(repo.find(42));
nodejs
Breakdown
1
if (new.target === AbstractRepository)
Detects if the abstract base class constructor was directly instantiated via new.
2
throw new TypeError(...)
Throws a type error to prevent instantiating abstract base contracts directly without sub-classing.
3
typeof this.find !== 'function'
Inspects the instantiated object to verify the concrete subclass has implemented the required interface contract.
4
${new.target.name}
Accesses the constructor name of the derived class that triggered the instantiation.