Gathering detailed insights and metrics for ts-has-property
Gathering detailed insights and metrics for ts-has-property
Gathering detailed insights and metrics for ts-has-property
Gathering detailed insights and metrics for ts-has-property
ts-has-own-property
Fix for Object.hasOwnProperty, which normally just returns a boolean, which is not good when you care about strong typing
@sounisi5011/ts-type-util-has-own-property
Fix the type definition of the `Object.prototype.hasOwnProperty()` method
@crabas0npm2/perspiciatis-voluptate-similique
security holding package
@crabas0npm2/vel-sapiente-accusamus
security holding package
Universal and better typed `hasOwnProperty` for IntelliSense. Supports checking: properties of all types; multiple keys at a time; and type of values.
npm install ts-has-property
Typescript
Module System
Min. Node Version
Node Version
NPM Version
68.6
Supply Chain
98
Quality
75
Maintenance
100
Vulnerability
99.6
License
TypeScript (99.38%)
Shell (0.62%)
Total Downloads
6,114
Last Day
1
Last Week
7
Last Month
20
Last Year
278
MIT License
5 Stars
87 Commits
1 Watchers
2 Branches
2 Contributors
Updated on Jan 03, 2023
Minified
Minified + Gzipped
Latest Version
2.1.3
Package Id
ts-has-property@2.1.3
Unpacked Size
25.65 kB
Size
8.27 kB
File Count
8
NPM Version
6.14.15
Node Version
12.22.6
Cumulative downloads
Total Downloads
Last Day
0%
1
Compared to previous day
Last Week
250%
7
Compared to previous week
Last Month
-53.5%
20
Compared to previous month
Last Year
-61.8%
278
Compared to previous year
1
8
Universal and better typed hasOwnProperty
for better IntelliSense - code hinting. Supports checking: properties of all types; multiple keys at a time; and optionally checks if the value(s) belongs to the specified type.
RU: Универсальный и более типизированный аналог hasOwnProperty
для улучшения подсказок при работе в IDE-шках (редакторах кода). Также, метод поддерживает проверку свойств всех типов данных, позволяет перечислить сразу несколько ключей, опционально можно задать проверку на тип значения, а также корректно работает с коллекциями, созданными через Object.create(null)
.
- Do not use
any
type, please.- Use
unknown
if you thing aboutany
.- If you working with third party module and have to suffer from
any
, sots-has-property
may be very useful, may-be...
1yarn add ts-has-property -T
or, if you prefer npm
:
1npm i ts-has-property -E
EN:
SemVer
is not guaranteed;
RU: СоблюдениеSemVer
не гарантируется.
Function arguments / Аргументы функции:
1import hasProperty from 'ts-has-property'; 2 3const data = anyThing(/* ... */); 4 5if (hasProperty(data, 'someKey')) { 6 data.someKey; // <- 100% exists 7 // @see "Demo / Демонстрация" section 8}
EN: If 1st argument is not an object =>
false
; tsc will inform you about typing errors if possible. @see Note.
RU: Если первым аргументом передан не объект, то функция вернётfalse
; tsc сообщит об ошибке, если сможет проверить тип передаваемого значения до рантайма. Подробнее: см. Замечание.
EN: Unlike the first version, all types are now supported as the first argument.
RU: С данной версии, проверяются свойства любого значения, передаваемого первым аргументом.
Required<>
values / Обязательность значений[ℹ️]:
any
=== 👎 &&unknown
=== 👍
EN: If you only need non-null
/undefined
property, there is shortcut for you, see listing below;
RU: В обычном режиме проверяется только наличие ключа, однако, если его значение может быть undefined
или null
, то в большинстве условиях потребуется дополнительная проверка для осуществления дальнейшего чейнинга значения. Поэтому, в функции предусмотрен шорткат, позволяющий проверить свойство на нененулевое значение:
1const data: { 2 title: string; 3 description?: string; // string | undefined 4 // ... 5} = getData(/* ... */); 6 7data.description = undefined; // - `data` has property `description` 8 9if ( 10 hasProperty(data, 'description', true) // 👈 `true` 11) { 12 // ... 13 console.log(data.description.toString()); 14} else { 15 console.log(`Data's own property 'description' has no value`); 16}
[ℹ️]:
any
=== 👎 &&unknown
=== 👍
EN: If we have a value that has a union type
, but only a certain one is required, there is a shortcut - 3rd argument, see listing below;
RU: Если значение свойства может принадлежать одному из нескольких типов, а требуется только определённый, то и на этот случай имеется шорткат:
1const data: Record< // - object 2 string, // - type of key 3 number | Array<number> // - type of value 4> = getData(/* ... */); 5 6const sum = hasProperty(data, 'key', 'array') // 👈 `'array'` 7 ? data.key.reduce((prev, cur) => prev + cur) // `data.key: Array<number>` 8 : data.key // `data.key: number`
Possible argument values / Возможные значения:
'boolean'
'string'
'number'
'object'
'array'
1const data: Record< // - object 2 string, // - type of key 3 'some' | 'union' | 'types' | 27 | 13 // - type of value 4> = getData(/* ... */); 5 6if (hasProperty(data, 'key', 'string')) { 7 data.key; // `data.key: 'some' | 'union' | 'types'` 8}
@see gif demo
object
properties / Свойства не-объектов1const data: Array<number | string> = []; 2 3if (hasProperty(data, 27, 'number')) { 4 const thisNumber = data[27]; // `data[27]: number` 5} 6 7if (hasProperty(data, 0, 'array')) { // type error, 8 // Array `data: Array<number | string>` has no `Array` items 9}
@see demo (2nd gif)
Не обязательно явной строкой указывать название ключа, как это демонстрируется в gif-ке, ключ также может храниться в
const
-те илиenum
-е. Главное, чтобы IDE была точно уверенна в содержимом передаваемого параметра.
Enum
member values / Пример с Enum
-ом1const obj: { 2 [key: string]: Array<string>, 3} = {}; 4 5enum Keys { 6 sth = 'something', 7} 8 9if (hasProperty(obj, Keys.sth)) { 10 obj./* IDE: something */; // см. изображение ниже 11}
1// ... 2 3if (hasProperty(obj, ['someKey', 'yetAnotherKey'])) { 4 obj./* IDE: */; 5 /* someKey */ 6 /* yetAnotherKey */ 7}
For versions 1.*.* only
EN: hasProperty
checks if 1st argument is a 'plain' object.
RU: Данная функция проверяет, является ли первый аргумент - обычным объектом.
Said Magomedov - GitHub // NPM // VK
EN: This project is licensed under the MIT License.
RU: Данный проект распространяется по MIT License.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
no SAST tool detected
Details
Reason
project is archived
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
15 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-04-28
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More