typemoq icon indicating copy to clipboard operation
typemoq copied to clipboard

Generating random objects from TS interfaces

Open ganqqwerty opened this issue 7 years ago • 1 comments

I don't know if it's a proper place to ask questions like this, but is it possible to have a ts interface like this:

export interface Employment {
  location: string;
  workload: number;
  from: Date;
  to: Date;
}
interface Employee {
  shortName: string;
  firstName: string;
  lastName: string;
  currentLocation: string;
  employments: Array<Employment>;
}

and get an real object full of auto-filled properties like here?

const e: Employee = TypeMoq.Mock.generateRandomOfType<Employee>(); 
e.shortName === 'some random string';
e.employments[0].workload === 42; 

ganqqwerty avatar Feb 27 '18 13:02 ganqqwerty

It's not really possible in this way, not yet anyhow.

Using a Proxy instance you can capture any property invocation, but at runtime you don't have type information for the property and typescript doesn't eject reflection metadata for interfaces so there's no way to do it completely as described i.e. you wouldn't be able to return the right types of data.

However, if you had a class you could get typescript to emit reflection metadata for properties and then read that metadata to automatically setup the properties with correct types. Couple that with something like fakerjs and it's possible to create such a mechanism.

That will only work with simple types - complex types aren't serialized into the reflection metadata in a way that would support this (yet).

mindlink avatar Apr 19 '18 11:04 mindlink