Deprecated: Function WP_Dependencies->add_data() was called with an argument that is deprecated since version 6.9.0! IE conditional comments are ignored by all supported browsers. in /home/www/wordpress/wp-includes/functions.php on line 6131

Deprecated: Function WP_Dependencies->add_data() was called with an argument that is deprecated since version 6.9.0! IE conditional comments are ignored by all supported browsers. in /home/www/wordpress/wp-includes/functions.php on line 6131
Skip to content

Use hasOwnProperty with Typescript

Overview

Typescript does not support hasOwnProperty() function like javascript. To archive this we need to create an own helper function:

type Prop = string | number | symbol;

function hasOwnProperty<X extends {}, Y extends Prop>(obj: X, prop: Y): obj is X & Record<Y, unknown> {
  return obj.hasOwnProperty(prop)

Typescript Code

type Prop = string | number | symbol;
const  y = {name: "Helmut", id: 333}

function hasOwnProperty<X extends {}, Y extends Prop>(obj: X, prop: Y): obj is X & Record<Y, unknown> {
  return obj.hasOwnProperty(prop)
}

let propertyName = 'name';
if (hasOwnProperty(y, propertyName) ) {
  if (typeof y.name === 'string' && y.name) {
    console.log("--- Property " + propertyName +  " found - Content: "  + y.name);
  }
}
else {
    console.log("--- Property " + propertyName + " not found");
  } 

propertyName = 'id';
if (hasOwnProperty(y, propertyName) ) {
  if (typeof y.name === 'string' && y.id) {
    console.log("--- Property " + propertyName +  " found - Content: "  + y.id);
  }
}
else {
    console.log("--- Property " + propertyName + " not found");
  } 

propertyName = 'name2';
if (hasOwnProperty(y, propertyName) ) {
  if (typeof y.name === 'string' && y.name2) {
    console.log("--- Property " + propertyName +  " found - Content: "  + y.name2);
  }
}
else {
    console.log("--- Property " + propertyName + " not found");
  } 

Output

[LOG]: "--- Property name found - Content: Helmut" 
[LOG]: "--- Property id found - Content: 333" 
[LOG]: "--- Property name2 not found" 

Reference

Published inTypescript

Be First to Comment

Leave a Reply