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.
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 .
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!
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 .
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With