Skip to content

angular-package/type

 
 

Repository files navigation

Packages

Useful packages based on the angular.io.

Package Description Status Readme
change-detection Improve application performance. In Progress Readme
prism Prism highlighter module. In Progress Readme
property Features to handle properties. In Progress Readme
ui User interface based on Spectre.css. In Progress Github
type Common types, type guards and type checkers. npm version Github | npm

angular-package/type

Common types, type guards and type checkers.

npm version GitHub issues GitHub forks GitHub stars GitHub license

// `guard` prefix functions.
import { 
  guardArray,
  guardBigInt,
  guardBoolean,
  guardFunction,
  guardInstance,
  guardKey,
  guardNull,
  guardNumber,
  guardObject,
  guardObjectKey,
  guardPrimitive,
  guardString,
  guardSymbol,
  guardType,
  guardUndefined
} from '@angular-package/type'; 
// `is` prefix functions.
import {
  isArray,
  isBigInt,
  isBoolean,
  isBooleanObject,
  isBooleanType,
  isDefined,
  isFunction,
  isInstance,
  isKey,
  isNull,
  isNumber,
  isNumberObject,
  isNumberType,
  isObject,
  isObjectKey,
  isObjectKeyIn,
  isPrimitive,
  isString,
  isStringObject,
  isStringType,
  isSymbol,
  isType,
  isUndefined
} from '@angular-package/type';
// `are` prefix functions.
import {
  areString
} from '@angular-package/type';
// `isNot` prefix functions.
import {
  isNotBoolean,
  isNotDefined,
  isNotFunction,
  isNotNull,
  isNotNumber,
  isNotString,
  isNotUndefined
} from '@angular-package/type';
// Object.
import { are, guard, is, isNot } from '@angular-package/type';
// Types.
import { Constructor, CycleHook, Func, Key, Primitive, Primitives, ResultCallback, Type, Types } from '@angular-package/type';

Features

How angular-package understands

Check

Is to check the inputted value to be the same as expected.

Type guard

Is to guard the parameter type to not let input unexpected value in the code editor.

Guard

Is a combination of both above to guard type in the code editor and to check inputted value.



Installation

Install @angular-package/type package with command:

npm i --save @angular-package/type

Callback

update

Default function to handle callback.

const resultCallback: ResultCallback = (result: boolean, value?: any): boolean => result;
Parameter Type Description
result boolean A boolean type value from the result of the check
value any Any type value from the check

The return value is a boolean type result from the check.

Custom function to handle callback.

const customCallback: ResultCallback = (result: boolean, value: any): boolean => {
  if (result === false) {
    throw new Error(`${value} must be a string`);
  }
  return result;
};

const stringResult = isString('Lorem ipsum', customCallback);

Check

are

Tne object contains prefixed with are functions.

const are: Are = {
  string: areString
};

areString

Use areString() or are.string() to check if any of all the values are a string.

const areString = (...value: any): boolean => check('string', ...value);
Parameter Type Description
...value any Any values to check

The return value is a boolean indicating whether or not all the values are an Array.

Example usage on playground


is

The object contains prefixed with is functions and prefixed with isNot functions in property not.

const is: Is = {
  array: isArray,
  bigInt: isBigInt, // deprecated
  bigint: isBigInt,
  boolean: isBoolean,
  booleanObject: isBooleanObject,
  booleanType: isBooleanType,
  defined: isDefined,
  function: isFunction,
  instance: isInstance,
  key: isKey,
  not: isNot,
  null: isNull,
  number: isNumber,
  numberObject: isNumberObject,
  numberType: isNumberType,
  object: isObject,
  objectKey: isObjectKey,
  objectKeyIn: isObjectKeyIn,
  primitive: isPrimitive,
  string: isString,
  stringObject: isStringObject,
  stringType: isStringType,
  symbol: isSymbol,
  type: isType,
  undefined: isUndefined
};

isArray

Use isArray() or is.array() to check if any value is an Array, Array instance, and object type.

const isArray: IsArray = <Type>(value: any, callback: ResultCallback = resultCallback): value is Array<Type> =>
  callback(
    typeOf(value) === 'array' &&
    Array.isArray(value) === true &&
    value instanceof Array === true &&
    typeof value === 'object',
    value
  );
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is an Array.

// Example usage
import { isArray } from '@angular-package/type';

const ARRAY_NUMBER = [1, 2, 3];
const ARRAY_STRING = ['a', 'b', 'c'];

isArray(ARRAY_NUMBER); // true
isArray<string>(ARRAY_STRING); // true

Example usage on playground


isBigInt

Use isBigInt() or is.bigint() to check if any value is a bigint type.

const isBigInt: IsBigInt = (value: any, callback: ResultCallback = resultCallback): value is bigint =>
  callback(typeOf(value) === 'bigint' && typeof value === 'bigint', value);
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a bigint.

// Example usage
import { isBigInt } from '@angular-package/type';

const BIGINT = 9007199254740991n;
const NUMBER = 27;

isBigInt(NUMBER); // false
isBigInt(BIGINT); // true

Example usage on playground | How to detect bigint type


isBoolean

Use isBoolean() or is.boolean() to check if any value is a boolean type not instance of Boolean and Object or object type instance of Boolean and Object.

const isBoolean: IsBoolean = (value: any, callback: ResultCallback = resultCallback): value is boolean =>
  callback(typeOf(value) === 'boolean' && (isBooleanType(value) || isBooleanObject(value)), value);
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a boolean.

// Example usage
import { isBoolean } from '@angular-package/type';

const BOOLEAN = false;
const BOOLEAN_INSTANCE = new Boolean(false);

isBoolean(BOOLEAN); // true
isBoolean(BOOLEAN_INSTANCE); // true

Example usage on playground | How to detect the boolean type


isBooleanObject

Use isBooleanObject() or is.booleanObject() to check if any value is an object type and instance of Boolean and Object.

const isBooleanObject: IsBooleanObject = (value: any, callback: ResultCallback = resultCallback): value is Boolean =>
  callback(typeof value === 'object' && value instanceof Boolean === true && value instanceof Object === true, value);
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a Boolean instance.

// Example usage
import { isBooleanObject } from '@angular-package/type';

const BOOLEAN = false;
const BOOLEAN_INSTANCE = new Boolean(false);

isBooleanObject(BOOLEAN); // false
isBooleanObject(BOOLEAN_INSTANCE); // true

isBooleanType

Use isBooleanType() or is.booleanType() to check if any value is a boolean type not an instance of Boolean and Object, and equal to true or false.

const isBooleanType: IsBooleanType = (value: any, callback: ResultCallback = resultCallback): value is boolean =>
  callback(
    value instanceof Boolean === false &&
    value instanceof Object === false &&
    typeof value === 'boolean' &&
    (value === true || value === false),
    value
  );
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a boolean type.

// Example usage
import { isBooleanType } from '@angular-package/type';

const BOOLEAN = false;
const BOOLEAN_INSTANCE = new Boolean(false);

isBooleanType(BOOLEAN); // true
isBooleanType(BOOLEAN_INSTANCE); // false

isDefined

Use isDefined() or is.defined() to check if an unknown value is not an undefined type and is not equal to undefined.

const isDefined: IsDefined = (value: unknown, callback: ResultCallback = resultCallback): boolean =>
  callback(typeOf(value) !== 'undefined' && typeof value !== 'undefined' && value !== undefined, value);
Parameter Type Description
value unknown An unknown value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is defined, not undefined.

// Example usage
import { isDefined } from '@angular-package/type';

const UNDEFINED = undefined;
let defined;

isDefined(UNDEFINED); // false
isDefined(defined); // false

isFunction

Use isFunction() or is.function() to check if any value is a function type, an instance of Function and Object.

const isFunction: IsFunction = (value: any, callback: ResultCallback = resultCallback): value is Func =>
  callback(
    typeOf(value) === 'function' &&
    typeof value === 'function' &&
    value instanceof Function === true &&
    value instanceof Object === true,
    value
  );
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a function.

// Example usage
import { isFunction } from '@angular-package/type';

type Func = (...param: any) => any;
class Class { x = 5; }
const FUNC: Func = (x: number): any => x + 5;

isFunction(Class); // true
isFunction(FUNC); // true
isFunction(() => 5); // true

Example usage on playground | How to detect function type


isInstance

Use isInstance() or is.instance() to check if any value is an object of a generic Obj type equal to an instance of Constructor type.

const isInstance: IsInstance = <Obj>(
    value: any,
    instance: Constructor<Obj>,
    callback: ResultCallback = resultCallback
  ): value is Obj =>
    callback(
      isObject<Obj>(value) ?
        isFunction(instance) ?
          value instanceof instance === true
        : false
      : false,
      value
    );
Parameter Type Description
value any Any value to compare with the instance
instance Constructor<Obj> A generic Obj Constructor type to create an instance to compare with the value
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is an instance of a generic Obj.

// Example usage
import { isInstance } from '@angular-package/type';

class Some { x = 127; }
class Two { y = 'Lorem ipsum'; }

const SOME = new Some();
const TWO = new Two();

isInstance<Some>(TWO, Some); // false
isInstance<Some>(SOME, Some); // true
isInstance<Some>(TWO, Two); // true and type error

Example usage on playground | How to detect constructor instance


isKey

Use isKey() or is.key() to check if any value is one of the string, number, or symbol.

const isKey: IsKey = (value: any, callback: ResultCallback = resultCallback): value is Key =>
  callback(isString(value) || isNumber(value) || isSymbol(value), value);
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a Key.

// Example usage
import { isKey } from '@angular-package/type';

const STRING = 'surname';
const STRING_INSTANCE = new String(STRING);
isKey(STRING); // true
isKey(STRING_INSTANCE); // true

const NUMBER = 27;
const NUMBER_INSTANCE = new Number(NUMBER);
isKey(NUMBER); // true
isKey(NUMBER_INSTANCE); // true

const SYMBOL_NUMBER: unique symbol = Symbol(NUMBER);
const SYMBOL_STRING: unique symbol = Symbol(STRING);
isKey(SYMBOL_NUMBER); // true
isKey(SYMBOL_STRING); // true

isNull

Use isNull() or is.null() to check if any value is an object type and equal to null.

const isNull: IsNull = (value: any, callback: ResultCallback = resultCallback): value is null =>
  callback(typeOf(value) === 'null' && typeof value === 'object' && value === null, value);
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is null.

// Example usage
import { isNull } from '@angular-package/type';

/**
 * typeof === 'object'
 * instanceof Function === false
 * instanceof Number === false
 * instanceof Object === false
 */
const NULL: any = null;
const NUMBER = 27;

isNull(NULL); // true
isNull(NUMBER); // false

Example usage on playground | How to detect null type


isNumber

Use isNumber() or is.number() to check if any value is a number type not an instance of Number and Object or object type instance of Number and Object.

const isNumber: IsNumber = (value: any, callback: ResultCallback = resultCallback): value is number =>
  callback(typeOf(value) === 'number' && isFinite(value) === true && (isNumberType(value) || isNumberObject(value)), value);
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a number.

Example usage on playground | How to detect a number type


isNumberObject

Use isNumberObject() or is.numberObject() to check if any value is an object type and instance of Number and Object.

const isNumberObject: IsNumberObject = (value: any, callback: ResultCallback = resultCallback): value is Number =>
  callback(typeof value === 'object' && value instanceof Number === true && value instanceof Object === true, value);
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a Number instance.

// Example usage
import { isNumberObject } from '@angular-package/type';

/**
 * typeof === 'number'
 * instanceof Function === false
 * instanceof Number === false
 * instanceof Object === false
 */
const NUMBER: any = 10304050;

/**
 * typeof === 'number'
 * instanceof Function === false
 * instanceof Number === false
 * instanceof Object === false
 */
const NUMBER_INSTANCE: any = Number(NUMBER);

/**
 * typeof === 'number'
 * instanceof Function === false
 * instanceof Number === true
 * instanceof Object === true
 */
const NUMBER_NEW_INSTANCE: any = new Number(NUMBER);

isNumberObject(NUMBER); // false
isNumberObject(NUMBER_INSTANCE); // false
isNumberObject(NUMBER_NEW_INSTANCE); // true

isNumberType

Use isNumberType() or is.numberType() to check if any value is a number type not an instance of Number and Object.

const isNumberType: IsNumberType = (value: any, callback: ResultCallback = resultCallback): value is number =>
  callback(value instanceof Number === false && value instanceof Object === false && typeof value === 'number', value);
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a number.

// Example usage
import { isNumberType } from '@angular-package/type';

/**
 * typeof === 'number'
 * instanceof Function === false
 * instanceof Number === false
 * instanceof Object === false
 */
const NUMBER: any = 10304050;

/**
 * typeof === 'number'
 * instanceof Function === false
 * instanceof Number === false
 * instanceof Object === false
 */
const NUMBER_INSTANCE: any = Number(NUMBER);

/**
 * typeof === 'number'
 * instanceof Function === false
 * instanceof Number === true
 * instanceof Object === true
 */
const NUMBER_NEW_INSTANCE: any = new Number(NUMBER);

isNumberType(NUMBER); // true
isNumberType(NUMBER_INSTANCE); // true
isNumberType(NUMBER_NEW_INSTANCE); // false

isObject

Use isObject() or is.object() to check if any value is an object of a generic Obj type and Object instance with the possibility of containing the key.

const isObject: IsObject = <Obj = object>(value: any, key?: Key): value is Obj =>
  (typeOf(value) === 'object' && typeof value === 'object' && value instanceof Object === true)
    ? isKey(key)
      ? key in value
    : true
  : false;
Parameter Type Description
value any Any value to check
key? Key Property name to find in the value

The return value is a boolean indicating whether or not the value is an object.

Example usage on playground | How to detect an object type

// Example usage
import { isObject } from '@angular-package/type';

/**
 * typeof === 'number'
 * instanceof Function === false
 * instanceof Number === false
 * instanceof Object === false
 */
const NUMBER: any = 10304050;

/**
 * typeof === 'number'
 * instanceof Function === false
 * instanceof Number === false
 * instanceof Object === false
 */
const NUMBER_INSTANCE: any = Number(NUMBER);

/**
 * typeof === 'number'
 * instanceof Function === false
 * instanceof Number === true
 * instanceof Object === true
 */
const NUMBER_NEW_INSTANCE: any = new Number(NUMBER);

/**
 * typeof === 'string'
 * instanceof Function === false
 * instanceof Object === false
 * instanceof String === false
 */
const STRING: any = '!@#$%^&*()abcdefghijklmnoprstuwyz';

/**
 * typeof === 'string'
 * instanceof Function === false
 * instanceof Object === false
 * instanceof String === false
 */
const STRING_INSTANCE: any = String(STRING);

/**
 * typeof === 'string'
 * instanceof Function === false
 * instanceof Object === true
 * instanceof String === true
 */
const STRING_NEW_INSTANCE: any = new String(STRING);

const SYMBOL_NUMBER: unique symbol = Symbol(NUMBER);
const SYMBOL_STRING: unique symbol = Symbol(STRING);

interface ObjectOne {
  'key as string'?: boolean;
  1030405027?: string;
  5?: string;
  [SYMBOL_NUMBER]?: string;
  [SYMBOL_STRING]?: number;
  x: number;
}

const OBJECT_ONE: ObjectOne = {
  'key as string': true,
  1030405027: 'key is number',
  5: 'key is also number',
  [NUMBER]: 'key is number',
  [STRING]: 'key is string',
  [SYMBOL_NUMBER]: 'key is symbol number',
  [SYMBOL_STRING]: 6,
  x: 3000
};

isObject(OBJECT_ONE); // true
isObject(OBJECT_ONE, 'key as string'); // true
isObject(OBJECT_ONE, STRING); // true
isObject(OBJECT_ONE, STRING_NEW_INSTANCE); // true
isObject(OBJECT_ONE, 1030405027); // true
isObject(OBJECT_ONE, NUMBER); // true
isObject(OBJECT_ONE, NUMBER_NEW_INSTANCE); // true
isObject(OBJECT_ONE, SYMBOL_NUMBER); // true
isObject(OBJECT_ONE, SYMBOL_STRING); // true

isObjectKey

Use isObjectKey() or is.objectKey() to check if any value is an object with its own specified keys of the Key. The function uses hasOwnProperty method to find the key.

const isObjectKey: IsObjectKey = <Type extends object>(
  value: any,
  key: Key | Key[],
  callback: ResultCallback = resultCallback
): value is Type =>
  callback(
    isObject<Type>(value) ?
      isArray(key) ?
        key.every(k => isKey(k) ? ({}).hasOwnProperty.call(value, k) === true : false)
      : isKey(key) ?
          ({}).hasOwnProperty.call(value, key)
        : false
    : false,
    value
  );
Parameter Type Description
value any Any value to check if it contains a specified key
key Key | Key[] A Key type or an array of Key type to check in the value
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is an object with its own specified keys.

// Example usage
import { isObjectKey } from '@angular-package/type';

/**
 * typeof === 'number'
 * instanceof Function === false
 * instanceof Number === false
 * instanceof Object === false
 */
const NUMBER: any = 10304050;

/**
 * typeof === 'string'
 * instanceof Function === false
 * instanceof Object === false
 * instanceof String === false
 */
const STRING: any = '!@#$%^&*()abcdefghijklmnoprstuwyz';

/**
 * typeof === 'number'
 * instanceof Function === false
 * instanceof Number === false
 * instanceof Object === false
 */
const NUMBER_INSTANCE: any = Number(NUMBER);

/**
 * typeof === 'number'
 * instanceof Function === false
 * instanceof Number === true
 * instanceof Object === true
 */
const NUMBER_NEW_INSTANCE: any = new Number(NUMBER);


/**
 * typeof === 'string'
 * instanceof Function === false
 * instanceof Object === false
 * instanceof String === false
 */
const STRING_INSTANCE: any = String(STRING);

/**
 * typeof === 'string'
 * instanceof Function === false
 * instanceof Object === true
 * instanceof String === true
 */
const STRING_NEW_INSTANCE: any = new String(STRING);

const SYMBOL_NUMBER: unique symbol = Symbol(NUMBER);
const SYMBOL_STRING: unique symbol = Symbol(STRING);

interface ObjectOne {
  'key as string'?: boolean;
  1030405027?: string;
  5?: string;
  [SYMBOL_NUMBER]?: string;
  [SYMBOL_STRING]?: number;
  x: number;
}

/**
 * typeof === 'object'
 * instanceof Boolean === false
 * instanceof Function === false
 * instanceof Number === false
 * instanceof Object === true
 * instanceof String === false
 * instanceof Symbol === false
 */
const OBJECT_ONE: ObjectOne = {
  'key as string': true,
  1030405027: 'key is number',
  5: 'key is also number',
  [NUMBER]: 'key is number',
  [STRING]: 'key is string',
  [SYMBOL_NUMBER]: 'key is symbol number',
  [SYMBOL_STRING]: 6,
  x: 3000
};

isObjectKey(OBJECT_ONE, STRING); // true
isObjectKey(OBJECT_ONE, STRING_NEW_INSTANCE); // true
isObjectKey(OBJECT_ONE, 1030405027); // true
isObjectKey(OBJECT_ONE, NUMBER); // true
isObjectKey(OBJECT_ONE, NUMBER_NEW_INSTANCE); // true
isObjectKey(OBJECT_ONE, SYMBOL_NUMBER); // true
isObjectKey(OBJECT_ONE, SYMBOL_STRING); // true

/**
 * typeof === 'function'
 * instanceof Class === false
 * instanceof Function === true
 * instanceof Object === true
 */
export class Class {

  1030405027 = 'my new number';
  5 = 'my number';

  firstName = 'My name';
  surname = 'Surname';

  x = NUMBER;
  y = STRING;

  get [NUMBER](): number {
    return this.x;
  }
  get [STRING](): string {
    return this.y;
  }

  get [SYMBOL_NUMBER](): number {
    return this.x;
  }

  get [SYMBOL_STRING](): string {
    return this.y;
  }
}

/**
 * typeof === 'object'
 * instanceof Class === true
 * instanceof Function === false
 * instanceof Object === true
 */
export const CLASS = new Class();

// One of the differences between the `in` operator and the `hasOwnProperty()` method is that it doesn't find a getter key
isObjectKey(CLASS, SYMBOL_NUMBER); // false
isObjectKey(CLASS, SYMBOL_STRING); // false
isObjectKey(CLASS, [SYMBOL_NUMBER, SYMBOL_STRING]); // false

isObjectKeyIn

new

Use isObjectKeyIn() or is.objectKeyIn() to check if any value is an Object with the key of the Key type by using the in operator. The function uses operator in to find the key.

const isObjectKeyIn: IsObjectKeyIn = <Type extends object>(
  value: any,
  key: Key | Key[],
  callback: ResultCallback = resultCallback
): value is Type =>
  callback(
    isObject<Type>(value) ?
      isArray(key) ?
        key.every(k => isKey(k) ? k in value : false)
      : isKey(key) ?
          key in value
        : false
    : false,
    value
  );
Parameter Type Description
value any Any value to check if it contains a specified key
key Key | Key[] A Key type or an array of Key type to check in the value
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is an object with the keys.

import { isObjectKeyIn } from '@angular-package/type';

/**
 * typeof === 'number'
 * instanceof Function === false
 * instanceof Number === false
 * instanceof Object === false
 */
export const NUMBER: any = 10304050;

/**
 * typeof === 'string'
 * instanceof Function === false
 * instanceof Object === false
 * instanceof String === false
 */
export const STRING: any = '!@#$%^&*()abcdefghijklmnoprstuwyz';

/**
 * typeof === 'symbol'
 * instanceof Boolean === false
 * instanceof Function === false
 * instanceof Number === false
 * instanceof Object === false
 * instanceof String === false
 * instanceof Symbol === false
 */
export const SYMBOL_NUMBER: unique symbol = Symbol(NUMBER);
export const SYMBOL_STRING: unique symbol = Symbol(STRING);

/**
 * typeof === 'function'
 * instanceof Class === false
 * instanceof Function === true
 * instanceof Object === true
 */
export class Class {

  1030405027 = 'my new number';
  5 = 'my number';

  firstName = 'My name';
  surname = 'Surname';

  x = NUMBER;
  y = STRING;

  get [NUMBER](): number {
    return this.x;
  }
  get [STRING](): string {
    return this.y;
  }

  get [SYMBOL_NUMBER](): number {
    return this.x;
  }

  get [SYMBOL_STRING](): string {
    return this.y;
  }
}

/**
 * typeof === 'object'
 * instanceof Class === true
 * instanceof Function === false
 * instanceof Object === true
 */
export const CLASS = new Class();

 // One of the differences between `in` operator and the `hasOwnProperty()` method is that it finds a getter key
isObjectKeyIn(CLASS, SYMBOL_NUMBER); // true
isObjectKeyIn(CLASS, SYMBOL_STRING); // true
isObjectKeyIn(CLASS, [SYMBOL_NUMBER, SYMBOL_STRING]); // true

isPrimitive

Use isPrimitive() or is.primitive() to check if any value is the Primitive type from a type of the Primitives type.

const isPrimitive: IsPrimitive = <T extends Primitive>(
  value: any,
  type: Primitives,
  callback: ResultCallback = resultCallback
): value is T => {
  if (isStringType(type)) {
    switch (type) {
      case 'bigint': return isBigInt(value, callback);
      case 'boolean': return isBooleanType(value, callback);
      case 'number': return isNumberType(value, callback);
      case 'null': return isNull(value, callback);
      case 'string': return isStringType(value, callback);
      case 'symbol': return isSymbol(value, callback);
      case 'undefined': return isUndefined(value, callback);
    }
  }
  return false;
};
Parameter Type Description
value any Any value to check if it's a Primitive from the type
type Primitives A string type from the Primitives to check the value
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a type from the Primitives.

Example usage on playground


isString

Use isString() or is.string() to check if any value is a string type, not instance of Object and String or object type and instance of String and Object.

const isString: IsString = (value: any, callback: ResultCallback = resultCallback): value is string =>
  callback(typeOf(value) === 'string' && (isStringType(value) || isStringObject(value)), value);
Parameter Type Description
value any Any value to check
callback ResultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a string type or String object.


isStringObject

Use isStringObject() or is.stringObject() to check if any value is an object type and instance of String and Object.

const isStringObject: IsStringObject = (value: any, callback: ResultCallback = resultCallback): value is String =>
  callback(value instanceof Object === true && value instanceof String === true && typeof value === 'object', value);
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a String instance.


isStringType

Use isStringType() or is.stringType() to check if any value is a string type and not instance of String and Object.

const isStringType: IsStringType = (value: any, callback: ResultCallback = resultCallback): value is string =>
  callback(value instanceof Object === false && value instanceof String === false && typeof value === 'string', value);
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a string type.


isSymbol

Use isSymbol() or is.symbol() to check if any value is a symbol type.

const isSymbol: IsSymbol = (value: any, callback: ResultCallback = resultCallback): value is symbol =>
  callback(typeOf(value) === 'symbol' && typeof value === 'symbol', value);
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a symbol.

Example usage on playground | How to detect symbol type


isType

Use isType() or is.type() to check if any value is the Type from a type of the Types type.

const isType: IsType = <T extends Type>(value: any, type: Types<T>, callback: ResultCallback = resultCallback): value is T => {
  if (isStringType(type)) {
    switch (type) {
      // Primitives.
      case 'bigint':
      case 'boolean':
      case 'number':
      case 'null' :
      case 'string':
      case 'symbol':
      case 'undefined': return isPrimitive(value, type, callback);
      // Function.
      case 'function': return isFunction(value, callback);
      // Object.
      case 'object': return isObject<T>(value);
    }
  } else if (isNotNull(type)) {
    return isInstance<T>(value, type, callback);
  }
  return false;
};
Parameter Type Description
value any Any value to check if its type is from the type
type Types<T> A string or generic Constructor type from the Types to check the value
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is the Type from a type of the Types.

Example usage on playground


isUndefined

Use isUndefined() or is.undefined() to check if any value is an undefined type and equal to undefined.

const isUndefined: IsUndefined = (value: any, callback: ResultCallback = resultCallback): value is undefined =>
  callback(typeOf(value) === 'undefined' && typeof value === 'undefined' && value === undefined, value);
Parameter Type Description
value any Any value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is undefined.

Example usage on playground | How to detect undefined type


isNot

Object isNot with all check is not functions.

const isNot: IsNot = {
  boolean: isNotBoolean,
  defined: isNotDefined,
  function: isNotFunction,
  null: isNotNull,
  number: isNotNumber,
  string: isNotString,
  undefined: isNotUndefined
};

isNotBoolean

Use isNotBoolean() or is.not.boolean() to check if an unknown value is not a boolean type, not equal to true or false and not an instance of a Boolean.

const isNotBoolean: IsNotBoolean = (value: unknown, callback: ResultCallback = resultCallback): boolean =>
  callback(
    typeOf(value) !== 'boolean' &&
    typeof value !== 'boolean' &&
    value instanceof Boolean === false &&
    value !== true &&
    value !== false,
    value
  );
Parameter Type Description
value unknown An unknown value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is not a boolean.


isNotDefined

Use isNotDefined() or is.not.defined() to check if an unknown value is an undefined type and is equal to undefined.

const isNotDefined: IsNotDefined = (value: unknown, callback: ResultCallback = resultCallback): boolean =>
  callback(typeOf(value) === 'undefined' && typeof value === 'undefined' && value === undefined, value);
Parameter Type Description
value unknown An unknown value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is not defined, is undefined.


isNotFunction

Use isNotFunction() or is.not.function() to check if an unknown value is not a function type and not an instance of Function.

const isNotFunction: IsNotFunction = (value: unknown, callback: ResultCallback = resultCallback): boolean =>
  callback(typeOf(value) !== 'function' && typeof value !== 'function' && value instanceof Function === false, value);
Parameter Type Description
value unknown An unknown value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is not a function.


isNotNull

Use isNotNull() or is.not.null() to check if an unknown value is not a null type and not equal to null.

const isNotNull: IsNotNull = (value: unknown, callback: ResultCallback = resultCallback): boolean =>
  callback(typeOf(value) !== 'null' && value !== null, value);
Parameter Type Description
value unknown An unknown value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is not null.


isNotNumber

Use isNotNumber() or is.not.number() to check if an unknown value is not a number type and not an instance of Number.

const isNotNumber: IsNotNumber = (value: any, callback: ResultCallback = resultCallback): boolean =>
  callback(
    typeOf(value) !== 'number' &&
    typeof value !== 'number' &&
    value instanceof Number === false,
    value
  );
Parameter Type Description
value unknown An unknown value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is not a number.


isNotString

Use isNotString() or is.not.string() to check if an unknown value is not a string type and not an instance of String.

const isNotString: IsNotString = (value: unknown, callback: ResultCallback = resultCallback): boolean =>
  callback(typeOf(value) !== 'string' && typeof value !== 'string' && value instanceof String === false, value);
Parameter Type Description
value unknown An unknown value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is not a string.


isNotUndefined

Use isNotUndefined() or is.not.undefined() to check if an unknown value is not an undefined type and not equal to undefined.

const isNotUndefined: IsNotUndefined = (value: unknown, callback: ResultCallback = resultCallback): boolean =>
  callback(typeOf(value) !== 'undefined' && typeof value !== 'undefined' && value !== undefined, value);
Parameter Type Description
value unknown An unknown value to check
callback ResultCallback=resultCallback ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is not undefined.

// Example usage with the problem
import { is } from '@angular-package/type';

interface Config {
  a?: string;
  b?: string;
}
const config: Config = {
  a: 'x',
  b: 'y'
};

function configFunction(value: string): string {
  return '';
}

// Cause typescript returns `boolean` this will generate a type error
if (is.not.undefined(config.a)) {
  configFunction(config.a);
}

// Cause typescript return `value is undefined` will not generate an error
if (!is.undefined(config.a)) {
  configFunction(config.a);
}

Guard

guard

The object contains prefixed with guard functions in is property.

const guardIs: GuardIs = {
  array: guardArray,
  bigint: guardBigInt,
  boolean: guardBoolean,
  function: guardFunction,
  instance: guardInstance,
  key: guardKey,
  number: guardNumber,
  null: guardNull,
  object: guardObject,
  objectKey: guardObjectKey,
  primitive: guardPrimitive,
  string: guardString,
  symbol: guardSymbol,
  type: guardType,
  undefined: guardUndefined
};
const guard: Guard = {
  is: guardIs
};

guardArray

Use guardArray() or guard.is.array() to guard the value to be an Array of a generic Type.

const guardArray: GuardArray = <Type>(value: Array<Type>, callback?: ResultCallback): value is Array<Type> =>
  isArray<Type>(value, callback);
Parameter Type Description
value Array<Type> A generic Type Array value to guard
callback? ResultCallback Optional ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is an Array of a generic Type.

Example usage on playground


guardBigInt

Use guardBigInt() or guard.is.bigint() to guard the value to be a bigint.

const guardBigInt: GuardBigInt = (value: bigint, callback?: ResultCallback): value is bigint =>
  isBigInt(value, callback);
Parameter Type Description
value bigint A bigint type value to guard
callback? ResultCallback Optional ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a bigint.


guardBoolean

Use guardBoolean() or guard.is.boolean() to guard the value to be any type of a boolean.

const guardBoolean: GuardBoolean = <B extends AnyBoolean>(value: B, callback?: ResultCallback): value is B =>
  isBoolean(value, callback);
Parameter Type Description
value B extends AnyBoolean An AnyBoolean type value to guard
callback? ResultCallback An Optional ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a boolean type or Boolean object.


guardFunction

Use guardFunction() or guard.is.function() to guard the value to be a Func type.

const guardFunction: GuardFunction = (value: Func, callback?: ResultCallback): value is Func =>
  isFunction(value, callback);
Parameter Type Description
value Func A Func type value to guard
callback? ResultCallback Optional ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a Func.

Example usage on playground


guardInstance

Use guardInstance() or guard.is.instance() to guard the value to be an object of a generic Obj type equal to an instance of Constructor type.

const guardInstance: GuardInstance = <Obj>(value: Obj, instance: Constructor<Obj>, callback?: ResultCallback): value is Obj =>
  isInstance<Obj>(value, instance, callback);
Parameter Type Description
value Obj An Obj type value to compare with the instance
instance Constructor<Obj> A generic Obj Constructor type to create an instance to compare with the value
callback? ResultCallback Optional ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is an instance of a generic Obj.


guardKey

Use guardKey() or guard.is.key() to guard the value to be one of the string, number, or symbol.

const guardKey: GuardKey = (value: Key, callback?: ResultCallback): value is Key => 
  isKey(value, callback);
Parameter Type Description
value Key A Key type value to guard
callback? ResultCallback Optional ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a Key.


guardNull

Use guardNull() or guard.is.null() to guard the value to be a null.

const guardNull: GuardNull = (value: null, callback?: ResultCallback): value is null =>
  isNull(value, callback);
Parameter Type Description
value null A null type value to guard
callback? ResultCallback Optional ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a null.


guardNumber

Use guardNumber() or guard.is.number() to guard the value to be any type of a number.

const guardNumber: GuardNumber = <N extends AnyNumber>(value: N, callback?: ResultCallback): value is N =>
  isNumber(value, callback);
Parameter Type Description
value N extends AnyNumber An AnyNumber type value to guard
callback? ResultCallback An Optional ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a number type or Number object.

Example usage on playground


guardObject

Use guardObject() or guard.is.object() to guard the value to be an object of a generic Obj type.

const guardObject: GuardObject = <Obj extends object>(value: Obj): value is Obj => isObject<Obj>(value);
Parameter Type Description
value Obj extends object A generic Obj type value to guard

The return value is a boolean indicating whether or not the value is an object of a generic Obj.

Example usage on playground


guardObjectKey

Use guardObjectKey() or guard.is.objectKey() to guard the value to be an object of a generic Obj type that contains the key property of the Key type.

const guardObjectKey: GuardObjectKey = <Obj extends object, Key extends keyof Obj>(value: Obj, key: Key): value is Obj =>
  guardObject<Obj>(value) ? isKey(key) ? key in value : true : false;
Parameter Type Description
value Obj A generic Obj type value that contains the key to guard
key Key A Key type name of the property that the value contains

The return value is a boolean indicating whether or not the value is an object of a generic Obj containing the Key.

Example usage on playground


guardPrimitive

Use guardPrimitive() or guard.is.primitive() to guard the value to be the Primitive from a type of the Primitives.

const guardPrimitive: GuardPrimitive =
  <Type extends Primitive>(value: Type, type: Primitives, callback?: ResultCallback): value is Type => 
    isPrimitive<Type>(value, type, callback);
Parameter Type Description
value Type extends Primitive A Primitive type value to guard
type Primitives A string type from the Primitives to check the value
callback? ResultCallback Optional ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is the Primitive from the type.

Example usage on playground


guardString

Use guardString() or guard.is.string() to guard the value to be any type of a string.

const guardString: GuardString = <S extends AnyString>(value: S, callback?: ResultCallback): value is S =>
  isString(value, callback);
Parameter Type Description
value S extends AnyString An AnyString type value to guard
callback? ResultCallback An Optional ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a string type or String object.

Example usage on playground


guardSymbol

Use guardSymbol() or guard.is.symbol() to guard the value to be a symbol.

const guardSymbol: GuardSymbol = (value: symbol, callback?: ResultCallback): value is symbol =>
  isSymbol(value, callback);
Parameter Type Description
value symbol A symbol type value to guard
callback? ResultCallback Optional ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a symbol.


guardType

Use guardType() or guard.is.type() to guard the value to be the Type from a type of the Types.

const guardType: GuardType = <T extends Type>(value: T, type: Types<T>, callback?: ResultCallback): value is T  =>
  isType<T>(value, type, callback);
Parameter Type Description
value T extends Type A Type value to guard with the type
type Types<T> A string or generic Constructor type from the Types to check the value
callback? ResultCallback Optional ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is a type from the Types.

Example usage on playground


guardUndefined

Use guardUndefined() or guard.is.undefined() to guard the value to be undefined.

const guardUndefined: GuardUndefined = (value: undefined, callback?: ResultCallback): value is undefined =>
  isUndefined(value, callback);
Parameter Type Description
value undefined A undefined type value to guard
callback ResultCallback Optional ResultCallback function to handle result before returns eg. to throw an Error

The return value is a boolean indicating whether or not the value is undefined.


Common types

AnyBoolean

type AnyBoolean = Exclude<boolean | Boolean, true | false>;

AnyNumber

type AnyNumber = number | Number;

AnyString

type AnyString = string | String;

Constructor

type Constructor<Type> = new (...args: any[]) => Type;

CycleHook

type CycleHook = 'ngAfterContentInit' | 'ngAfterContentChecked' | 'ngAfterViewInit' | 'ngAfterViewChecked'
  | 'ngAfterViewChecked' | 'ngOnInit' | 'ngOnDestroy' | 'ngOnChanges';

Func

Function type.

type Func = (...param: any) => any;

Key

Name of the object property.

type Key =  number | string | symbol;

Primitive

All Primitive types.

type Primitive = bigint | boolean | null | number | string | symbol | undefined;

Primitives

All Primitive types as string.

type Primitives = 'bigint' | 'boolean' | 'null' | 'number' | 'symbol' | 'string' | 'undefined';

ResultCallback

type ResultCallback = <Obj>(result: boolean, value?: any) => boolean;

Type

Main types.

type Type = Func | object | Primitive;

Types

Main types as string.

type Types<Obj> = Constructor<Obj> | 'function' | 'object' | Primitives;

Experimental

BigIntObject

The object handles creating and getting the BigInt with BigInt().

class BigIntObject {
  static set set(value: any) {
    PrimitiveObject.bigint = BigInt(value);
  }
  static get get(): BigInt {
    return PrimitiveObject.bigint;
  }
}

Create a new BigInt by assign value to the set property.

BigIntObject.set = 1n;

Get created BigInt with the get property.

const bigint: BigIntObject = BigIntObject.get;

BooleanObject

The object handles creating and getting the Boolean object instance with Boolean().

class BooleanObject {
  /**
   * `false` when empty, 0, null, '', false
   * `true` when 'true', 'false', 'Su Lin whatever', [], {}, true
   */
  static set set(value: any) {
    PrimitiveObject.boolean = new Boolean(value);
  }
  static get get(): Boolean {
    return PrimitiveObject.boolean;
  }
}

Create a new Boolean instance by assign value to the set property.

BooleanObject.set = false;

Get created Boolean instance with the get property.

const booleanInstance: Boolean = BooleanObject.get;

NumberObject

The object handles creating and getting the Number object instance with Number().

class NumberObject {
  static set set(value: any) {
    PrimitiveObject.number = new Number(value);
  }
  static get get(): Number {
    return PrimitiveObject.number;
  }
}

Create a new Number instance by assign value to the set property.

NumberObject.set = 'my number instance';

Get created Number instance with the get property.

const numberInstance: Number = NumberObject.get;

PrimitiveObject

The object to store static primitive objects.

class PrimitiveObject  {
  static bigint: BigInt;
  static boolean: Boolean;
  static number: Number;
  static string: String;
  static symbol: Symbol;
}

StringObject

The object handles creating and getting the String object instance with String().

class StringObject {
  static set set(value: any) {
    PrimitiveObject.string = new String(value);
  }
  static get get(): String {
    return PrimitiveObject.string;
  }
}

Create a new String instance by assign value to the set property.

StringObject.set = 'my string instance';

Get created String instance with the get property.

const stringInstance: String = StringObject.get;

SymbolObject

The object handles creating and getting the Symbol object instance with Symbol().

class SymbolObject {
  static set set(value: string | number | undefined) {
    PrimitiveObject.symbol = Symbol(value);
  }
  static get get(): Symbol {
    return PrimitiveObject.symbol;
  }
}

Create a new symbol by assigning value to the set property.

SymbolObject.set = 'my symbol';

Get created symbol with the get property.

const symbol: Symbol = SymbolObject.get;

isParam

Method decorator to check the type and return undefined if it's not the same as expected.

function isParam(...param: Array<string>): MethodDecorator {
  return (target: Func | object, key: string | symbol, descriptor: any): any => {
    const originalMethod = descriptor.value;

    descriptor.value =  function(): void {
      if (is.array(param) && is.defined(arguments)) {
        param.forEach((name: string, index: number) => {
          if (is.number(index) && index < arguments.length) {
            if (is.defined(arguments[index])) {
              switch (name) {
                case 'number':
                  if (is.number(arguments[index]) === false) {
                    arguments[index] = undefined;
                  }
                  break;
                case 'object':
                  if (is.object(arguments[index]) === false) {
                    arguments[index] = undefined;
                  }
                  break;
                case 'string':
                  if (is.string(arguments[index]) === false) {
                    arguments[index] = undefined;
                  }
                  break;
              }
            }
          }
        });
      }
      const result = originalMethod.apply(this, arguments);
      return result;
    };

    return descriptor;
  };
}

Example usage.

// Example  usage
const STRING: any = '!@#$%^&*()abcdefghijklmnoprstuwyz';
const NUMBER: any = 10304050;
// TestClass
class TestClass {
  @isParam('object', 'string', 'number')
  public testMethod(object?: any, firstName?: any, age?: any): { object: any, firstName: any, age: any } {
    return {object, firstName, age};
  }
}
const resultTRUE = new TestClass().testMethod({firstName: 'NoName'}, STRING, NUMBER);
const resultFALSE = new TestClass().testMethod(NUMBER, {firstName: 'NoName'}, STRING);

resultTRUE === {
  object: {firstName: 'NoName'},
  string: '!@#$%^&*()abcdefghijklmnoprstuwyz',
  number: 10304050
};

resultTRUE === {
  object: undefined,
  string: undefined,
  number: undefined
};

GIT

Commit

Versioning

Semantic Versioning 2.0.0

Given a version number MAJOR.MINOR.PATCH, increment the:

  • MAJOR version when you make incompatible API changes,
  • MINOR version when you add functionality in a backwards-compatible manner, and
  • PATCH version when you make backwards-compatible bug fixes.

Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.

FAQ How should I deal with revisions in the 0.y.z initial development phase?

The simplest thing to do is start your initial development release at 0.1.0 and then increment the minor version for each subsequent release.

How do I know when to release 1.0.0?

If your software is being used in production, it should probably already be 1.0.0. If you have a stable API on which users have come to depend, you should be 1.0.0. If you’re worrying a lot about backwards compatibility, you should probably already be 1.0.0.

License

MIT © angular-package (license)