Composition and mixins
Concept and syntax
Composition builds behavior by delegating to another object rather than inheriting its entire class. A mixin can instead produce a class with an added capability; typed constructor-based mixins are a later generic application. Prefer explicit capability contracts and delegation when independent behavior is enough. The second example is a small class-producing mixin specialized to the Meter constructor type. It returns a derived class that adds label while keeping read.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
interface Reader {read():number;}class Meter implements Reader {read(){return 7;}}class Report {constructor(private source:Reader){}show(){return "n="+this.source.read();}}console.log(new Report(new Meter()).show(),new Report({read:()=>0}).show());function withLabel(Base:typeof Meter){return class extends Base {label(){return "meter";}};}const Labeled=withLabel(Meter);console.log(new Labeled().label());Expected output:
n=7 n=0meterCommon mistake
Intentionally invalid; compile separately and do not execute.
interface Reader {read():number;}class Report {constructor(private source:Reader){}}new Report({read:()=>"bad"});Expected diagnostic: TS2322. The delegated capability must return number. Supply a compatible Reader.
Practice and recap
Replace Meter with a second Reader without changing Report.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Composition and mixins — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
interface Reader {read():number;}class Meter implements Reader {read(){return 7;}}class Report {constructor(private source:Reader){}show(){return "n="+this.source.read();}}console.log(new Report(new Meter()).show(),new Report({read:()=>0}).show());function withLabel(Base:typeof Meter){return class extends Base {label(){return "meter";}};}const Labeled=withLabel(Meter);console.log(new Labeled().label());Which diagnostic and explanation match the rejected example under the lesson settings?
interface Reader {read():number;}class Report {constructor(private source:Reader){}}new Report({read:()=>"bad"});