EN
TypeScript - check if object has property or function
0 points
In TypeScript it is possible to check if object has property or method (function) in following ways.
This approach checks only entries that are directly inside object.
xxxxxxxxxx
1
interface Student {
2
name: string;
3
age: number;
4
}
5
6
const student: Student = {
7
name: 'John',
8
age: 25,
9
};
10
11
console.log(student.hasOwnProperty('name')); // true
12
console.log(student.hasOwnProperty('age')); // true
13
console.log(student.hasOwnProperty('country')); // false
Output:
xxxxxxxxxx
1
true
2
true
3
false
This approach checks elements that are inside prototype chain.
xxxxxxxxxx
1
interface Student {
2
name: string;
3
age: number;
4
}
5
6
const student: Student = {
7
name: 'John',
8
age: 25,
9
};
10
11
console.log('name' in student); // true
12
console.log('age' in student); // true
13
console.log('country' in student); // false
Output:
xxxxxxxxxx
1
true
2
true
3
false
Note: be careful during using this approach because of inherited properties and methods e.g. true value for 'toString' in student expression.