How to create an object dynamically from an interface?

Asked

Viewed 849 times

1

I have the following interface:

interface IInterface {
    Method1: (param1: any) => any;
    Method2: (param2: string[]) => any;
}

I wish that from it I could create objects dynamically that implement and that all methods do the same thing, depending on the parameters passed.

I tried it this way:

const keys = Reflect.ownKeys({} as IInterface);

let obj = {};
for (let key in keys) {
    obj[key] = (...params) => {
        console.log(`Chamou a função ${key}!`);
        return params.length > 0 ? params[0] : false;
    };
}

let obj2: IInterface = obj as IInterface; // Aqui eu teria a instancia de IInterface

But to no avail.

  • I’ve never seen this object before "Reflect".

  • I think you’re confusing the concepts a little bit. Interfaces are created to define a standard contract that different objects must obey. An interface does not define as the method will be implemented. It seems that a simple class definition would solve your problem... Perhaps if you explained better in the question what would be the use of this mechanism you want, a better solution could be proposed.

1 answer

2


TL;DR: You can’t do this.


Typescript is a superset Javascript. I imagine you already know this, so I won’t be long on this story that everyone already knows. The point is that Typescript code itself is not executed. What really happens is that it is transformed into Javascript. Thus, what actually runs is Javascript code.

Thus, bearing in mind that the interfaces typescript are not taken to the Javascript code (generated through the "transpilation" of the TS code), you cannot generate any value dynamically through them. You can only use them (until the time I write this answer) to ensure the safety of types (such as inference, object definition, classes and the like) in your code.

What you should do is create the object manually:

interface Person {
  name: string
  age: number
  gender: 'M' | 'F'
}

const luiz: Person = {
  name: 'Luiz Felipe',
  age: 16,
  gender: 'M'
}
  • I don’t know if this is a good justification, taking into account that Typescript could take the interface metadata together with the generated code if it identified that it would be used. Anyway you answered my question on TL;DR. :)

  • Yeah, but so far, it doesn’t take the interfaces to the generated JS code as output... Like you said yourself, it "could" do it. It would be pretty cool, alias!! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.