Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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.

like image 790
zeroin Avatar asked Mar 30 '16 12:03

zeroin


People also ask

How do you check if an object does not have a property in JavaScript?

hasOwnProperty() method Every JavaScript object has a special method object. hasOwnProperty('myProp') that returns a boolean indicating whether object has a property myProp . hero. hasOwnProperty('name') returns true because the property name exists in the object hero .

How do you check if an object contains an object?

Use the has() method to check if a Set contains an object, e.g. set.has(obj) . The object has to be passed by reference to the has method to get a reliable result. The has method tests for the presence of a value in a Set and returns true if the value is contained in the Set . Copied!

How do you check if an object has an attribute in JavaScript?

JavaScript provides you with three common ways to check if a property exists in an object: Use the hasOwnProperty() method. Use the in operator. Compare property with undefined .

How do you check if a property exists in an array of objects?

Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false. Example: html.


1 Answers

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.

like image 67
NineBerry Avatar answered Sep 18 '22 23:09

NineBerry