I have this TypeScript code which uses overloads on a function declaration. This code works as expected.
function identity(x: string): string;
function identity(x: number): number;
function identity(x: string | number): string | number {
return x;
}
const a = identity('foo') // string
const b = identity(1) // number
const c = identity({}) // type error (expected)
I am trying to achieve the equivalent of this using function expressions instead of function declarations, however I get a type error:
/* Type '(x: string | number) => string | number' is not assignable to type '{ (x: string): string; (x: number): number; }'.
Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string' */
const identity: {
(x: string): string;
(x: number): number;
} = (x: string | number): string | number => x;
I want to know how I can achieve the same effect of overloading the function but with function expressions.