Files
scriptc/tests/diagnostics/constructor-returns-instance-super.ts
T
Malte UblandClaude Opus 5.5 11c97074e2 Answer the object a constructor returns from new
A class constructor's `return expr` was evaluated and dropped, so
`new C()` answered the constructed instance even where Node answers the
returned object (`if (C.instance) return C.instance;` built a second
instance).

A return that yields an instance of the class itself stores it in a
per-class result slot, read and cleared by one helper at every
construction site (direct new, class values, the checked dynamic
construction dispatchers, record-to-class coercion). A return of any
other object refuses with SC1090 (compile time in TypeScript, a
deferred fence in JavaScript); a JavaScript value typed only at run time
is tested when it returns. super() into a class that can return an
existing instance refuses, since Node would rebind the subclass's this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 14:42:18 -07:00

16 lines
387 B
TypeScript

// `super()` into a constructor that can return an existing instance would
// rebind the subclass's `this` to that instance.
class Shared {
static one: Shared | undefined = undefined;
constructor() {
if (Shared.one) return Shared.one;
Shared.one = this;
}
}
class Derived extends Shared {
constructor() {
super();
}
}
console.log(new Derived() instanceof Derived);