Home > OS >  How to recognize if a parameter is an enum or an array of enums?
How to recognize if a parameter is an enum or an array of enums?

Time:11-17

I want to provide to a function either an enum value, or an array of enum values. To do it, I have created a function:

export enum SettingType {
  hairColors ='haircolors',
  hatSizes = 'hatsizes'
}

public getSettings(settingTypes: SettingType | SettingType[]) {
  if (settingType instanceOf SettingType) {
     //Fetch data for one setting type
  } else {
     //Fetch data for all settings types
  }
}

public theUsage() {
  getSettings(SettingType.hairColors);
  getSettings([ SettingType.hairColors, SettingType.hatSizes ]);
}

The function theUsage shows how I would like to use the getSettings method. Either I want to provide one setting type, or many setting types. Than getSettings depending on if it is one setting type or more setting types will properly return the data.

Unfortunately, when I am doing it, I get an error stating that:

The right-hand side of an 'instanceof' expression must be of type 'any'
or of a type assignable to the 'Function' interface type.

How to check if settingTypes is an enum value or an array of enum values?

CodePudding user response:

The instanceof operator only works with classes or functions as the error message says. Use Array.isArray() to differentiate between arrays and non-arrays.

function getSettings(settingTypes: SettingType | SettingType[]) {
  if (Array.isArray(settingTypes)) {
    settingTypes
    // ^? settingTypes: SettingType[]
  } else {
    settingTypes
    // ^? settingTypes: SettingType
  }
}

Playground

CodePudding user response:

The instanceof operator only works with classes or functions as the error message says. Use Array.isArray() to differentiate between arrays and non-arrays.enter image description here

  • Related