Faker.js: Random value from Typescript enum (string literal)?

Created on 11 Sep 2017  路  4Comments  路  Source: Marak/faker.js

Given the following example TypeScript string enum:

export enum PaycheckFrequency {
  WEEKLY = 'weekly',
  EVERY_TWO_WEEKS = 'every two weeks',
  MONTHLY = 'monthly',
  OTHER = 'other',
}

Would it be possible to use Faker to randomly return one property as a value?

It's possible to do the following, but it only returns strings, and the arrayElement() method wants numbers correlating to indexes.

const randomPaycheckFrequency =
      PaycheckFrequency[
        faker.random.arrayElement(Object.getOwnPropertyNames(PaycheckFrequency))
];

Most helpful comment

I did get this to work:

```typescript
const randomPaycheckFrequency =
PaycheckFrequency[
faker.helpers.replaceSymbolWithNumber(
faker.random.arrayElement(Object.getOwnPropertyNames(PaycheckFrequency))
)
];

All 4 comments

I'd imagine you could write an intermediary function that would transform the arguments into the format you need?

Sorry, I'm not really using TypeScript in production so I'm not 100% fluent with it's latest syntaxes.

I did get this to work:

```typescript
const randomPaycheckFrequency =
PaycheckFrequency[
faker.helpers.replaceSymbolWithNumber(
faker.random.arrayElement(Object.getOwnPropertyNames(PaycheckFrequency))
)
];

Looks good to me.

Closing.

In case someone comes across this again as I did, this issue inspired me to create this solution using object values:

const randomPaycheckFrequency = faker.random.arrayElement(Object.values(PaycheckFrequency))
Was this page helpful?
0 / 5 - 0 ratings

Related issues

Aleyasen picture Aleyasen  路  6Comments

JeffBeltran picture JeffBeltran  路  5Comments

Deilan picture Deilan  路  3Comments

pvpshoot picture pvpshoot  路  4Comments

minhchu picture minhchu  路  3Comments