This question is about method overloading in TypeScript. I can define the interface Api without any problems. However if I implement it I get the error blow. I check which signature is called by checking the type of arg and return the right type accordingly. However the code does not compile. Unfortunately I can't find anything about overloading in the official TS docs.
interface Api {
test(arg: string): string;
test(arg: number): string[];
}
const api: Api = {
test(arg: string | number) {
if (typeof arg === "string") {
return "string";
}
return ["string", "string"];
},
};
Type '(arg: string | number) => string[] | "string"' is not assignable to type '{ (arg: string): string; (arg: number): string[]; }'.
Type 'string[] | "string"' is not assignable to type 'string'.
Type 'string[]' is not assignable to type 'string'.ts(2322)