どうも、ちょげ(@chogetarou)です。
メソッドを使ってObject(オブジェクト)にプロパティ(property)が存在するかどうか確認する方法を紹介します。
方法

メソッドを使ってObject(オブジェクト)のプロパティ(property)の存在チェックをするには、hasOwnProperty()を使います。
まず、ObjectからhasOwnProperty()を呼び出します。
そして、hasOwnProperty()の引数に、プロパティを指定します。
//obj=オブジェクト、prop=プロパティ
obj.hasOwnProperty(prop)
上記のhasOwnProperty()は、呼び出したObject(オブジェクト)にプロパティが存在すれば「true」、存在しなければ「false」を返します。
使用例
type Numbers = {
[key: string]: number
}
const nums: Numbers = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
}
console.log(nums.hasOwnProperty("six"))
console.log(nums.hasOwnProperty("one"))
console.log(nums.hasOwnProperty("five"))
出力:
[LOG]: false
[LOG]: true
[LOG]: true
コメント