Socket
Book a DemoInstallSign in
Socket

ts-has-property

Package Overview
Dependencies
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-has-property

Universal and better typed `hasOwnProperty` for IntelliSense. Supports checking: properties of all types; multiple keys at a time; and type of values.

latest
Source
npmnpm
Version
2.1.3
Version published
Maintainers
1
Created
Source

ts-has-property

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.

npm version Build Status Coverage Status jest

RU: Универсальный и более типизированный аналог hasOwnProperty для улучшения подсказок при работе в IDE-шках (редакторах кода). Также, метод поддерживает проверку свойств всех типов данных, позволяет перечислить сразу несколько ключей, опционально можно задать проверку на тип значения, а также корректно работает с коллекциями, созданными через Object.create(null).

  • Do not use any type, please.
  • Use unknown if you thing about any.
  • If you working with third party module and have to suffer from any, so ts-has-property may be very useful, may-be...

Navigation / Навигация

Read on repo-page

Installing / Установка

yarn add ts-has-property -T

or, if you prefer npm:

npm i ts-has-property -E

EN: SemVer is not guaranteed;
RU: Соблюдение SemVer не гарантируется.

Usage / Использование

Function arguments / Аргументы функции:

  • the value to inspect / проверяемый элемент
  • the key to check / искомый ключ
import hasProperty from 'ts-has-property';

const data = anyThing(/* ... */);

if (hasProperty(data, 'someKey')) {
  data.someKey; // <- 100% exists
  // @see "Demo / Демонстрация" section
}

@see Examples
Смотрите Примеры

Major versions / Основные версии

1.*.*

EN: If 1st argument is not an object => false; tsc will inform you about typing errors if possible. @see Note.
RU: Если первым аргументом передан не объект, то функция вернёт false; tsc сообщит об ошибке, если сможет проверить тип передаваемого значения до рантайма. Подробнее: см. Замечание.

2.*.*

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`);
}

Value type check / Принадлежность значения типу

[ℹ️]: 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'
One more example
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

Non-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)

Demo / Демонстрация

После проверки стандартным Object.hasOwnProperty, VSCode не предлагает проверенного ключа, а после проверки при помощи hasProperty ключ в подсказках предлагается

Не обязательно явной строкой указывать название ключа, как это демонстрируется в 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 */; // см. изображение ниже
}

Названия ключа из enum-а

Multiple keys / Несколько ключей

// ...

if (hasProperty(obj, ['someKey', 'yetAnotherKey'])) {
  obj./* IDE:               */;
      /*     someKey        */
      /*     yetAnotherKey  */
}

Type check / Проверка типа

При проверке на базовые типы, функция возвращает true только значения, которое соответствует ему. При этом сохраняются пользовательские интерфейсы.

Если искомый тип не может существовать значении, IDE-шка предупредит

Note / Замечание

For versions 1.*.* only

Не объект первым аргументом - ts-ошибка

EN: hasProperty checks if 1st argument is a 'plain' object.
RU: Данная функция проверяет, является ли первый аргумент - обычным объектом.

Author / Автор

Said Magomedov - GitHub // NPM // VK

License / Лицензия

EN: This project is licensed under the MIT License.
RU: Данный проект распространяется по MIT License.

Keywords

type

FAQs

Package last updated on 21 Sep 2021

Did you know?

Socket

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.

Install

Related posts