SharePointBeginner
SharePointBeginner

Reputation: 359

Match a string[] values to enum val, and convert matches to enum[] type

I have a string[] where the values I first want to compare to an enum, keep the matches and then convert/create a new var where string[] will become enum[] type instead. Preferably without type assertion (code guideline we have). Maybe with a Array.some function or the like.

Example. Assume I have this enum:

enum myEnum {
 apple: 'apple',
 orange: 'orange'
 }

I have a string[] with the following values:

['banana', 'apple', 'orange']

After matching it with the enum, I will have this left:

['apple', 'banana'] of type string[]

Now, I want to either convert or create a new variable that has the same values, but of type "myEnum" instead.

['apple', 'banana'] of type [myEnum]

How can I do that?

Upvotes: 0

Views: 683

Answers (1)

Son Nguyen
Son Nguyen

Reputation: 1777

You can use type assertion in TypeScript like so:

['apple', 'banana'] as myEnum[];

This is an example of the complete function:

enum myEnum {
  apple = 'apple',
  orange = 'orange'
}

function getFavoriteFruits(fruits: string[]): myEnum[] {
  return fruits.filter(fruit => fruit in myEnum) as myEnum[];
}

getFavoriteFruits(['apple', 'banana', 'orange', 'grapes']);

Upvotes: 1

Related Questions