ยท hands on
Function Overloading Explained
This article provides a code example of a Calculator class in TypeScript that can add numbers or strings. The add method converts the inputs to numbers, adds them together, and returns the result as a number or string depending on the input types.
Please write two sentences here. Yeah, two.
Contents
Heading
Description of content goes here.
export type NumberLike = number | string;
export class Calculator {
static add(a: number, b: number): number;
static add(a: string, b: string): string;
static add(a: NumberLike, b: NumberLike): NumberLike {
const toNumber = (x: NumberLike): number => (typeof x === 'string' ? parseInt(x, 10) : x);
const result = toNumber(a) + toNumber(b);
if (typeof a === 'string' && typeof b === 'string') {
return `${result}`;
}
return result;
}
}
const result = Calculator.add('1', '1');
console.log(typeof result); // "string"
console.log(result); // "2"