0

I'm creating a helper method to generate data for our tests. All I want is to be able to get the keys and types of the values of T so I can use it to create mocked values.

export class GenericMockFactory<T extends { id: number }>> {

makeMockModel(): T {
    return {
      //Mocked Data Here
    }
  }
}

So let's say T is

Model {
  id: number
  name: string
  country: string
}

And I have the mockFactory as

const mockFactory = GenericMockFactory<Model>

I'd like the return of mockFactory.makeMockModel() to be the Model object with values set as `any_${key}` if the type of the property is string and 1 if it's a number. For the example above:

{
  id: 1
  name: 'any_name'
  country: 'any_country'
}

What I've tried:

Object.entries(T).forEach(), which would be my go to if I had the object instantiated, I can't pass in a type, it seems.

brightpants
  • 415
  • 1
  • 4
  • 28
  • This is similar to [this question](https://stackoverflow.com/questions/59480160/typescript-check-object-by-type-or-interface-at-runtime-with-typeguards-in-2020). The static type system is erased upon transpiling TS to JS, so the only way to do this is to make JS "schema" objects that represent TS types. You can do it manually, or use a custom TS transformer to do it programmatically. – jcalz Nov 03 '20 at 19:44

1 Answers1

0

This could help: https://stackoverflow.com/a/43572554/8350634

function mockObject(obj) {
    const newObj = {};
    const keys = Object.keys(obj);
    for(const key of keys) {
        if(typeof newObj[key] == "string") {
            newObj[key] = 'any' + key;
        } else {
        
            newObj[key] = 1;
        }
    }
    return newObj;
}
Michel Vorwieger
  • 692
  • 5
  • 14