Hello Friends đź‘‹,
Welcome To Infinitbility! ❤️
TypeScript almost has the same syntax as javascript to check object has a key or not, in this tutorial, we will learn multiple ways to check object has a key or not in typescript.
Now, we are going to learn below three ways to check object keys exist or not.
hasOwnProperty()
methodif..else
method() ? : ;
ternary method
Let start today’s tutorial How to check if a JSON object has a key in typescript?
Before we move to check all three methods with examples, let first create an example object which we can use in all the below examples.
interface userInterface {
id: number,
name: string,
};
let user: userInterface = { id: 1, name: 'infinitbility' };
hasOwnProperty()
method
When inheritance is an important part of the structure of your application, the difference is that it will result in true
even for properties inherited by parent objects. hasOwnProperty() doesn’t. It will only return true if the object has that property directly - not one of its ancestors.
interface userInterface {
id: number,
name: string,
};
let user: userInterface = { id: 1, name: 'infinitbility' };
user.hasOwnProperty("id");
user.hasOwnProperty("example");
Output
if..else
method
if..else
also can handle to check key exists or not in objects.
Here is a list of falsy values:
false
0 (zero)
-0 (negative zero)
0n (BigInt zero)
"", '', `` (empty string)
null
undefined
NaN (not a number)
interface userInterface {
id: number,
name: string,
};
let user: userInterface = { id: 1, name: 'infinitbility' };
if(user.id){
true;
} else {
false;
}
if(user.example){
true;
} else {
false;
}
Output
() ? : ;
ternary method
Ternary method work like the same if..else
method, but you can use it as a shorthand.
interface userInterface {
id: number,
name: string,
};
let user: userInterface = { id: 1, name: 'infinitbility' };
(user.id) ? true : false;
(user.example) ? true : false;
Output
Thanks for reading…