Search code examples
javascriptarraystypescriptunion-types

Is there a way to call array prototype methods on union types?


Consider following code as example:


    class Something {

      public getItems(): string | string[] {

        return items;
      }

    } 

Is it Possible to access to the array prototype method on calling getItems() ?

Something like this ?

let something = new Something();

const items = something.getItems();

items.filter(i => i.length > 2); // here for example 


Solution

  • The only issue why you cant is the type getItems returns and it is string | string[]. The string part is a problem, as string has no Array prototype. In order to use the value returned by getItems we need to narrow the type by type guard.

    const items = something.getItems(); // items is string | string[]
    
    if (typeof items !== 'string') {
      // now type is narrowed to string[]
      items.filter(i => i.length > 2); // fully type safe
    } else {
      // here you have a string
    }
    
    

    We can also do that more consist by narrowing the structure to the array of strings also for string.

    const items = something.getItems(); // items is string | string[]
    // in line below I am bringing both possible values into array structure
    const finalItems = typeof items === 'string' ? [items] : items; 
    finalItems.filter(i => i.length > 2); // fully type safe
    
    

    The important in above is [items] where I put single string value into array, thanks that finalItems has only one type - string[]