CodePark/ questions / Polymorphism: classes vs unions
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › Polymorphism: classes vs unions

You want format(x: number) and format(x: string) on one class, like method overloading in Java. How do you do it in TypeScript?

Write overload signatures, then one implementation that checks the argument type at runtime

Write overload signatures followed by one implementation. For example: format(x: number): string; format(x: string): string; format(x: number | string): string { ... }. Callers see only the overload signatures. The single body checks the type with typeof. JavaScript has only one function per name, so the types are erased and one body must handle every case.

"Write two
format methods with different parameter types" is tempting for Java or C# developers. In TypeScript it is a "Duplicate function implementation" error. Often a union parameter, or two clearly named methods, is simpler than overloads.