You get this error when TypeScript expects a constructor or class reference, but the polymorphic `this` instance type is supplied instead.
The special `this` type always refers to an instance, but `extends`, `new`, and constructor constraints require a class, constructor signature, or `typeof` reference. When a mixin or helper tries to reuse the instance-side `this` in those positions—such as `class Derived extends this`, `new this()`, or `T extends this`—the compiler raises TS2509 because `this` cannot stand for the constructor side of the class.
Create a reusable constructor alias and use it to constrain the base class rather than the instance this:
type Constructor<T = {}> = new (...args: any[]) => T;
function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
timestamp = new Date();
};
}This keeps TBase on the constructor side, so the mixin never mentions the instance this in a place that expects a class type.
Static methods can see the constructor by typing this as T extends typeof Base:
class Base {
static make<T extends typeof Base>(this: T) {
return new this();
}
}Here this is still polymorphic, but the constraint T extends typeof Base keeps the compiler on the constructor side and avoids TS2509.
Reserve the instance this for methods, accessors, or this parameters so the compiler always knows it describes the subtype:
class Fluent {
setName(this: this, name: string) {
return Object.assign(this, { name });
}
}Do not try to reuse that same this type for extends, implements, or new clauses; those positions need constructor-like types instead.
Every class in TypeScript has two faces: the instance shape that flows through this, and the static constructor shape that appears in extends, implements, and new expressions. TS2509 is the compiler's way of reminding you that the instance this can only be used where the compiler already knows it is dealing with an instance; otherwise you must lift the type to typeof this or an explicit constructor signature. Mixins, factory helpers, and new expressions almost always belong to the static side, so anchor their generics to constructors instead of the polymorphic instance type.
Function expression requires a return type
Function expression requires a return type
Value of type 'string | undefined' is not iterable
How to fix "Value is not iterable" in TypeScript
Type 'undefined' is not assignable to type 'string'
How to fix "Type undefined is not assignable to type string" in TypeScript
Type narrowing from typeof check produces 'never'
How to fix "Type narrowing produces never" in TypeScript
Type parameter 'T' has conflicting constraints
How to fix "Type parameter has conflicting constraints" in TypeScript