lhk lhk - 3 months ago 20x
Javascript Question

Interface type check with Typescript

This question is the direct analogon to Class type check with TypeScript

I need to find out at runtime if a variable of type any implements an interface. Here's my code:

interface A{

var a:any={member:"foobar"};

if(a instanceof A) alert(a.member);

If you enter this code in the typescript playground, the last line will be marked as an error, "The name A does not exist in the current scope". But that isn't true, the name does exist in the current scope. I can even change the variable declaration to
var a:A={member:"foobar"};
without complaints from the editor. After browsing the web and finding the other question on SO I changed the interface to a class but then I can't use object literals to create instances.

I wondered how the type A could vanish like that but a look at the generated javascript explains the problem:

var a = {
member: "foobar"
if(a instanceof A) {

There is no representation of A as an interface, therefore no runtime type checks are possible.

I understand that javascript as a dynamic language has no concept of interfaces. Is there any way to type check for interfaces?

The typescript playground's autocompletion reveals that typescript even offers a method
. How can I use it ?


There is no way to runtime check an interface.

Additionally, I don't think it is likely that this will become a feature in the future according to the discussion on Codeplex. There are some techniques in that discussion that may work for you though, which are mostly about using some conventions to make something like type checking possible by adding an __implements property to all of your objects. It isn't really the same though.