Answer the question
In order to leave comments, you need to log in
How to fix No overload matches TS error?
There is something like this code:
// реализация
function providerGetItem(id: number): Item
function providerGetItem(id: number[]): Item[]
function providerGetItem(id: number | number[]): Item | Item[] {
return typeof id === 'number' ? {id} : id.map(id => ({id}))
}
// Абстракция
function getItem(id: number): Item
function getItem(id: number[]): Item[]
function getItem(id: number | number[]): Item | Item[] {
return providerGetItem(id) // <-- TS2769: No overload matches this call
}
providerGetItem(id)
results in an error:TS2769: No overload matches this call.
Overload 1 of 2, '(myAnimeListId: number): Promise<Series | undefined>', gave the following error.
Argument of type 'number | number[]' is not assignable to parameter of type 'number'.
Type 'number[]' is not assignable to type 'number'.
Overload 2 of 2, '(myAnimeListId: number[]): Promise<Series[]>', gave the following error.
Argument of type 'number | number[]' is not assignable to parameter of type 'number[]'.
Type 'number' is not assignable to type 'number[]'.
typeof id === 'number' ? providerGetItem(id) : providerGetItem(id)
Answer the question
In order to leave comments, you need to log in
In your code - in the implementation, you set a vinaigrette of types - and of the same name - and the compiler gets confused - which one to use - remove the extra ones - and leave the general one (where you can pass either a number or an array with a number) - and everything will work.
Or there is another option like what you suggested - they will check the input type of the argument - that is, on if-s - if a number - then one return, if the array is different (set the same for testing) - everything works - only more code.
type Item = {id: number}
function providerGetItem(id: number | number[]): Item | Item[] {
return typeof id === 'number' ? {id} : id.map(id => ({id}))
}
function getItem(id: number | number[]): Item | Item[] {
return providerGetItem(id);
}
console.log(getItem(1))
console.log(getItem([2]))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question