Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Code working on one compiler but failing on the other

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Type ‘T’ is not assignable to type ‘T[]’.

enter image description here

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?

>Solution :

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);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading