zeroin zeroin - 3 months ago 19
TypeScript Question

Check if an object (or just a class) has a property

Lets say I have a class:

module MyModule {
export class MyClass {
x:number;
y:number;
}
}


Then I have a string, "x". How can I check if MyClass has property "x"?

If I create an instance of MyClass and then do:

myClassInstance.hasOwnProperty("x");


it returns false unless x has a default value set. But I don't want to set default values for each property. It would be best if I even could do this without creating instance of MyClass.

Answer

TypeScript is compiled to JavaScript before execution. In the final JavaScript code, the type information from TypeScript is not available anymore. So there is no possibility to check TypeScript type information at runtime.


If you want to do a check at compile-time, you can use interfaces as in the following example:

interface IHasX
{
    x:any;
}

class MyClassA {
    x:number;
    y:number;
}

class MyClassB {
    y:number;
}

function Test(param: IHasX)
{
    // Do something with param.x 
}

var objA = new MyClassA();
var objB = new MyClassB();

Test(objA);
Test(objB);

The last line Test(objB); will fail to compile because the TypeScript compiler knows that objB is of type MyClassB and that that class has no property named x as required by the interface IHasX.

Comments