V
V
Vladimir Golub2021-07-08 12:48:58
typescript
Vladimir Golub, 2021-07-08 12:48:58

How to fix an iterator bug with the spread operator if the function can return an array or an object?

There is a function that can return an array or an object:

public static getSymbols(getSymbolsOnly = false): string[] | { symbols: string[], group: string } {
    const symbols = ['Symbol 1', 'Symbol 2'];

    if (getSymbolsOnly) {
      return symbols;
    }
    
    return {
      symbols: symbols,
      group: 'Group name',
    }
  }


I want to use its result in a spread statement
const symbols = InstrumentsService.getSymbols(true);

          assetSymbols = [
            ...symbols
          ]


There is an error: TS2488 Type string[] | { symbols: string[], group: string } must have a [Symbol.iterator]() method that return an iterator

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WbICHA, 2021-07-08
@RazerVG

https://www.typescriptlang.org/play?#code/JYOwLgpg...

interface SomeType {}

class SomeClass {
    static getSymbols(): SomeType;
    static getSymbols(getSymbolsOnly: true): string[];
    static getSymbols(getSymbolsOnly: false): SomeType;
    static getSymbols(getSymbolsOnly: boolean = false): string[] | SomeType {
        if(getSymbolsOnly) {
            return [];
        }
        return {};
    }
}

const t1 = SomeClass.getSymbols(); // SomeType
const t2 = SomeClass.getSymbols(true); // string[]
const t3 = SomeClass.getSymbols(false); // SomeType

I
Ilya, 2021-07-08
@sarapinit

const assetSymbols = Array.isArray(symbols) ? [...symbols] : [...symbols.symbols];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question