简体   繁体   中英

Function doesn't work when tested with typescript?

I have a strange problem. I have the below function in js:

const removeDuplicates = (inputData) => {
  return [
    ...new Map(inputData.map((data) => [JSON.stringify([data.x, data.y, data.v]), data])).values()
  ];
};

And I'm testing it like so in a jest typescript test:

it('removeDuplicates', () => {
    const expectedObject = [
    { x: 'G', y: 'B', v: '12345' },
    { x: 'A', y: 'L', v: '12345' },
    { x: 'A', y: 'W', v: '123' },
    { x: 'A', y: 'W', v: '1234' }
];
    
    
    const inputData = [
      { x: 'G', y: 'B', v: '12345' },
      { x: 'A', y: 'L', v: '12345' },
      { x: 'A', y: 'L', v: '12345' },
      { x: 'A', y: 'W', v: '123' },
      { x: 'A', y: 'W', v: '1234' },
      { x: 'A', y: 'W', v: '1234' }
    ];
    expect(removeDuplicates(inputData)).toEqual(expectedObject);
  });

When the test is in a js file it passes, when I convert the test file to a ts file it, fails and the function returns nothing? Any ideas?

Seems like the compiler doesn't like it without the compiler option ''--downlevelIteration'. Did you set this?

Type 'IterableIterator<unknown>' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.ts(2569)

You could use Array.from instead:

type MyThing = { x: string; y: string; v: string };

const removeDuplicates = (inputData: MyThing[]): MyThing[] =>
  Array.from(
    new Map(
      inputData.map((data) => [JSON.stringify([data.x, data.y, data.v]), data])
    ).values()
  );

You should also consider using an external library for such trivial tasks. Eg Ramda's uniq function should do exactly the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM