1

I'm looking to create an object from a typescript interface that will store initial empty values:

// Interface I'm looking to mock
interface IMyInterface {
  name: string;
  posts: string[];
}

From this interface, I would need to initialize an object with initial values based on the interface keys and type, something like:

const initObjFromInterface = (interface: any) => {
  // do something
  return initObject;
}

const initializedObj = initObjFromInterface(IMyInterface);

Note that I don't know the keys of the interface passed as an argument the initObjFromInterface function!

The returned value of the initObjFromInterface function should be:

console.log(initializedObj);

/* should output:
{
  name: "",  // empty string
  posts: []  // empty array
}
*/
4
  • Does this answer your question? Typescript interface default values Commented May 18, 2020 at 18:47
  • Thanks @ritaj but this is not answering the question. I need to initialize the object without knowing what the interface will be passed by with empty values, in the example, an empty string and an empty array. Commented May 18, 2020 at 18:52
  • don't think you will be able to pass an interface as an argument to a function because interface is just a type and can't be used as a value Commented May 18, 2020 at 19:09
  • You're right @Yousaf, there might need to create an Object or using Proxy to do so but not sure right now how to solve this tho! Commented May 18, 2020 at 19:14

1 Answer 1

1

You can't do that as stated in comments.

You have to store somewhere your instance of empty object.

const emptyObject: IMyInterface = {
  name: '',
  posts: []
}

And pass some unique value to function so it can determine which empty object of interface to get.

const initObjFromInterface = <T>(interfaceName: string) => {
  if(interfaceName === "IMyInterface") {
    return emptyObject as any as T;
  }

  return {} as T;
}

I sure the code above can be designed better ( perhaps type guards and type inferring )

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but this won't work for my case. I need to start with an interface and create the object from there. I'm pretty sure it can be done in some way so I'll keep working on it and I'll write the answer when I'll find before someone find it!
Let me know as I would like also to know how you can materialize typescript types into javascript!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.