Adapter Pattern For Interface Bridging
Implement an adapter to bridge incompatible interfaces with type-safe conversion for legacy integration.
Code
interface NewLogger{log(level:string,msg:string):void;}interface LegacyLogger{writeLog(severity:number,message:string):void;}export class LoggerAdapter implements NewLogger{constructor(private legacy:LegacyLogger){}log(level:string,msg:string):void{const severityMap:Record<string,number>={debug:10,info:20,warn:30,error:40};this.legacy.writeLog(severityMap[level]??20,msg);}}export function adaptLogger(legacy:LegacyLogger):NewLogger{return new LoggerAdapter(legacy);}How the snippet works
The working surface is the class LoggerAdapter and the function adaptLogger — everything else is wiring.
The result is a fresh construction, so callers can keep their originals.
Using it
LoggerAdapter is what another module would consume; nothing else here is load-bearing for callers.
FAQ
- Does `LoggerAdapter` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. The file defines `adaptLogger` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.