#Return Object based on Typescript Type or Interface

6 messages · Page 1 of 1 (latest)

inland viper
#

I want to create a Object with all props and empty values based on a given type.

For example:

type User = {
  name: string
}

export const populateArrayWithOption = (
  arrayToPopulate: Array<any>,
): Array<any> => {

  // the following is pseudo and what I actually look for
  return [someWayToGenerateAObjectBasedOnType(User), ...arrayToPopulate];

  /**
  * Output of someWayToGenerateAObjectBasedOnType(User) should be:
  * { name: "" }
  */

};

PS. I know about the any type, its example code.

violet cave
#

Types don't exist at runtime, so if what you're looking for is an object of type User with some default values, you have to define that object yourself, then referencing it where you need it (better with spread operator).
If you're looking to function to generate the object with passed values, you want a class to leverage its constructor, or a factory function.

inland viper
#

Alright, is it possible to generate a class based on a type or interface? 😄

#

Thanks for the explanation first of all

inland viper
#

Makes sense that I can't use something in runtime that doesn't exist at runtime.
The only way to do what I want to have would be to use a class but then my idea doesn't work in it's full potential. But okay, I guess I can't change that