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