The typescript playground is giving me the following errors:
No overload matches this call. Overload 1 of 3, '(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T', gave the following error. Type 'T[]' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'T[]'. Overload 2 of 3, '(callbackfn: (previousValue: never[], currentValue: T, currentIndex: number, array: T[]) => never[], initialValue: never[]): never[]', gave the following error. Type 'T[]' is not assignable to type 'never[]'. Type 'T' is not assignable to type 'never'.
and
Type 'T' is not assignable to type 'T[]'.
function myFilter<T>(arr: T[], cb: (v: T) => boolean): T[] {
const a = arr.reduce(
(acc, val) => (cb(val) === true ? [...acc, val] : acc),
[]
);
return a;
}
const c = myFilter([1, 3, 4, 5], (v) => v === 3);
console.log(c);
I'm using : https://www.typescriptlang.org/play But when i use : https://stackblitz.com/edit/typescript-playground-xt7e2y
Everything is fine and i get no errors? Why is the official typescript playground complaining and how do i fix it? or is it just a bug?
CodePudding user response:
I don't know which version or config is used in stackbliz
so it is hard to say why you are not getting error.
However, the problem is in empty array because empty array, by the default, is infered as never[]
.
In order to fix this error, you need to use explicit argument for reduce
.
function myFilter<T>(arr: T[], cb: (v: T) => boolean): T[] {
const a = arr.reduce<T[]>( // TS is aware now that [] is T[]
(acc, val) => cb(val) === true ? [...acc, val] : acc,
[]
);
return a;
}
const c = myFilter([1, 3, 4, 5], (v) => v === 3);
console.log(c);