boo1ean / casual

Fake data generator for javascript
3.03k stars 152 forks source link

Custom Generator Types #79

Open Darkbladecr opened 6 years ago

Darkbladecr commented 6 years ago

I am relatively new to Typescript and I have been trying to read the most appropriate way to extend the current types available on Casual to accomodate custom generators. For example:

import * as casual from 'casual';

casual.define('stripeCard', (): CasualCard => {
    return {
        card: {
            number: '4242424242424242',
            exp_month: casual.integer(1, 12),
            exp_year: casual.integer(2019, 2020),
            cvc: casual.integer(100, 999),
        },
    };
});

But whatever I try does not seem to work? Does anyone have experience extending the current index.d.ts?

rewop commented 6 years ago

I have the same problem. Anyone know how we should handle it?

cmvanb commented 6 years ago

edit: Nevermind. This doesn't work. I can't get the typescript compiler to accept custom types without hacking the casual index.d.ts.

You need to extend the Casual namespace and declare your types in a .d.ts file adjacent to your example code.

If your file above is named example.ts, then example.d.ts is the following:

declare namespace Casual {
  interface Casual {
    stripeCard: CasualCard;
  }
}

This works for me with typescript 2.9.2, tslint 5.10.0 and casual 1.5.19.

rewop commented 6 years ago

This is how I worked around it to add oneOf custom generator:

import * as casual from 'casual';

interface Generators extends Casual.Generators {
  _oneOf: <T>(values: T[]) => T;
  functions(): functions;
}

interface functions extends Casual.functions {
  oneOf: <T>(values: T[]) => T;
}

const extendedCasual = casual as Generators & Casual;

const testVar = extendedCasual._oneOf(config.contentTypes);
KyleDavisDev commented 4 years ago

Hey all, is the above workaround still the best option for this? Has this been looked into from the maintainer?

KyleDavisDev commented 4 years ago

My workaround was to simply create a function which returned the generated data that I am interested in.

For example, the generateValidPassword function takes in a length (or default 8) and will return a random string of letters between that passed number and 3x that amount.

export const generateValidPassword = (MIN_PASSWORD_LENGTH: number = 8) => {
  // generate length between minimum length and 3x the minimum length
  const _randomLength = casual.integer(MIN_PASSWORD_LENGTH, 3*MIN_PASSWORD_LENGTH)

  // turn generated length into random letters
  return new Array(_randomLength).fill(null).map(casual._letter).join("");
}

When trying to define this as a generator, TS would give me an error but as a normal function TS is fine with it. Hope this helps someone.