I have a challenge where I need to pass an Array<number|string>
to a function that accepts Array<number|string>
and returns either an Array<number>
or an Array<string>
.
Unfortunately, the method overloading doesn't seem to be working as expected. What could be the issue preventing it from functioning correctly?
user.model.ts
export interface User {
text: Array<string | number>;
}
user.service.ts
import { Injectable } from "@angular/core";
@Injectable({
providedIn: "root"
})
export class UserService {
public getText(text: Array<string>): Array<string>;
public getText(text: Array<number>): Array<number>;
public getText(text: Array<string | number>): Array<string | number> {
return text;
}
}
app.component.ts
export class AppComponent implements OnInit {
title = "CodeSandbox";
constructor(private userService: UserService) {}
ngOnInit() {
const user: User = {
text: ["string"]
};
this.userService.getText(user.text);
}
}
Error:
No overload matches this call.
Overload 1 of 2, '(text: string[]): string[]', gave the following error.
Argument of type '(string | number)[]' is not assignable to parameter of type 'string[]'.
Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.
Overload 2 of 2, '(text: number[]): number[]', gave the following error.
Argument of type '(string | number)[]' is not assignable to parameter of type 'number[]'.
Type 'string | number' is not not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.ts(2769)
Repo: https://codesandbox.io/s/eloquent-resonance-ilfvm?file=/src/app/app.component.ts