
Security News
Crates.io Users Targeted by Phishing Emails
The Rust Security Response WG is warning of phishing emails from rustfoundation.dev targeting crates.io users.
ts-has-property
Advanced tools
Universal and better typed `hasOwnProperty` for IntelliSense. Supports checking: properties of all types; multiple keys at a time; and type of values.
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...
yarn add ts-has-property -T
or, if you prefer npm
:
npm i ts-has-property -E
EN:
SemVer
is not guaranteed;
RU: СоблюдениеSemVer
не гарантируется.
Function arguments / Аргументы функции:
import hasProperty from 'ts-has-property';
const data = anyThing(/* ... */);
if (hasProperty(data, 'someKey')) {
data.someKey; // <- 100% exists
// @see "Demo / Демонстрация" section
}
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
, то в большинстве условиях потребуется дополнительная проверка для осуществления дальнейшего чейнинга значения. Поэтому, в функции предусмотрен шорткат, позволяющий проверить свойство на нененулевое значение:
const data: {
title: string;
description?: string; // string | undefined
// ...
} = getData(/* ... */);
data.description = undefined; // - `data` has property `description`
if (
hasProperty(data, 'description', true) // 👈 `true`
) {
// ...
console.log(data.description.toString());
} else {
console.log(`Data's own property 'description' has no value`);
}
[ℹ️]:
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: Если значение свойства может принадлежать одному из нескольких типов, а требуется только определённый, то и на этот случай имеется шорткат:
const data: Record< // - object
string, // - type of key
number | Array<number> // - type of value
> = getData(/* ... */);
const sum = hasProperty(data, 'key', 'array') // 👈 `'array'`
? data.key.reduce((prev, cur) => prev + cur) // `data.key: Array<number>`
: data.key // `data.key: number`
Possible argument values / Возможные значения:
'boolean'
'string'
'number'
'object'
'array'
const data: Record< // - object
string, // - type of key
'some' | 'union' | 'types' | 27 | 13 // - type of value
> = getData(/* ... */);
if (hasProperty(data, 'key', 'string')) {
data.key; // `data.key: 'some' | 'union' | 'types'`
}
@see gif demo
object
properties / Свойства не-объектовconst data: Array<number | string> = [];
if (hasProperty(data, 27, 'number')) {
const thisNumber = data[27]; // `data[27]: number`
}
if (hasProperty(data, 0, 'array')) { // type error,
// Array `data: Array<number | string>` has no `Array` items
}
@see demo (2nd gif)
Не обязательно явной строкой указывать название ключа, как это демонстрируется в gif-ке, ключ также может храниться в
const
-те илиenum
-е. Главное, чтобы IDE была точно уверенна в содержимом передаваемого параметра.
Enum
member values / Пример с Enum
-омconst obj: {
[key: string]: Array<string>,
} = {};
enum Keys {
sth = 'something',
}
if (hasProperty(obj, Keys.sth)) {
obj./* IDE: something */; // см. изображение ниже
}
// ...
if (hasProperty(obj, ['someKey', 'yetAnotherKey'])) {
obj./* IDE: */;
/* someKey */
/* yetAnotherKey */
}
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.
FAQs
Universal and better typed `hasOwnProperty` for IntelliSense. Supports checking: properties of all types; multiple keys at a time; and type of values.
We found that ts-has-property demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The Rust Security Response WG is warning of phishing emails from rustfoundation.dev targeting crates.io users.
Product
Socket now lets you customize pull request alert headers, helping security teams share clear guidance right in PRs to speed reviews and reduce back-and-forth.
Product
Socket's Rust support is moving to Beta: all users can scan Cargo projects and generate SBOMs, including Cargo.toml-only crates, with Rust-aware supply chain checks.