Rain Zhao
Rain Zhao

Reputation: 31

Compare two interfaces at runtime

I want to check if two interfaces are equal at runtime and then execute some code. I noticed a library conditional-type-checks that can compare types and returns a true or false type, but I am unsure of how to use it for my case.

This is what I have so far type IDialogUnchanged = IsExact<IDialog, IDialogOrig>;

which returns a true or false type

Upvotes: 2

Views: 1471

Answers (1)

Mike Sar
Mike Sar

Reputation: 107

Short: You can't. But they are hacks/workarounds/ways that can give you similar results, if you can change your requirements.

Long: Interfaces doesn't exists at run-time, so there is no way you can extract data about its members and/or compare them. Interfaces are design time tools, for you, for auto-complete etc. They vanish on run-time. However, there are few other options.

  1. You can emit types info and then retrieve it on run-time. I am not aware of any way to get full type info on runtime(like Java or C# reflection, but maybe some tools already exists). With this package (reflect-metadata) you can emit constructor params types and then work with them.
  2. If you have objects as instances of specific interfaces/classes, you can always compare them key by key, using Object.keys(obj) - it returns array of field names in given type(doesn't work with interfaces, as I mention, does not exist on runtime).
  3. Also, instanceof operator may be the thing that you need. It will return true if an object is an instace of given class. If you will perform check for both types(say A and B) you want to compare (obj instanceof A && obj instanceof B), where B extends A and obj is of type B, you will get true as a result of this statement.

Hope you can work you way out. If not, please provide more details or provide that library's name. Regards.

Upvotes: 3

Related Questions