Giter VIP home page Giter VIP logo

is's Introduction

is

Type check values

For example, is.string('๐Ÿฆ„') //=> true

Highlights

Install

npm install @sindresorhus/is

Usage

import is from '@sindresorhus/is';

is('๐Ÿฆ„');
//=> 'string'

is(new Map());
//=> 'Map'

is.number(6);
//=> true

Assertions perform the same type checks, but throw an error if the type does not match.

import {assert} from '@sindresorhus/is';

assert.string(2);
//=> Error: Expected value which is `string`, received value of type `number`.

Assertions (except assertAll and assertAny) also support an optional custom error message.

import {assert} from '@sindresorhus/is';

assert.nonEmptyString(process.env.API_URL, 'The API_URL environment variable is required.');
//=> Error: The API_URL environment variable is required.

And with TypeScript:

import {assert} from '@sindresorhus/is';

assert.string(foo);
// `foo` is now typed as a `string`.

Named exports

Named exports allow tooling to perform tree-shaking, potentially reducing bundle size by including only code from the methods that are used.

Every method listed below is available as a named export. Each method is prefixed by either is or assert depending on usage.

For example:

import {assertNull, isUndefined} from '@sindresorhus/is';

API

is(value)

Returns the type of value.

Primitives are lowercase and object types are camelcase.

Example:

  • 'undefined'
  • 'null'
  • 'string'
  • 'symbol'
  • 'Array'
  • 'Function'
  • 'Object'

This method is also exported as detect. You can import it like this:

import {detect} from '@sindresorhus/is';

Note: It will throw an error if you try to feed it object-wrapped primitives, as that's a bad practice. For example new String('foo').

is.{method}

All the below methods accept a value and return a boolean for whether the value is of the desired type.

Primitives

.undefined(value)
.null(value)
.string(value)
.number(value)

Note: is.number(NaN) returns false. This intentionally deviates from typeof behavior to increase user-friendliness of is type checks.

.boolean(value)
.symbol(value)
.bigint(value)

Built-in types

.array(value, assertion?)

Returns true if value is an array and all of its items match the assertion (if provided).

is.array(value); // Validate `value` is an array.
is.array(value, is.number); // Validate `value` is an array and all of its items are numbers.
.function(value)
.buffer(value)
.blob(value)
.object(value)

Keep in mind that functions are objects too.

.numericString(value)

Returns true for a string that represents a number satisfying is.number, for example, '42' and '-8.3'.

Note: 'NaN' returns false, but 'Infinity' and '-Infinity' return true.

.regExp(value)
.date(value)
.error(value)
.nativePromise(value)
.promise(value)

Returns true for any object with a .then() and .catch() method. Prefer this one over .nativePromise() as you usually want to allow userland promise implementations too.

.generator(value)

Returns true for any object that implements its own .next() and .throw() methods and has a function definition for Symbol.iterator.

.generatorFunction(value)
.asyncFunction(value)

Returns true for any async function that can be called with the await operator.

is.asyncFunction(async () => {});
//=> true

is.asyncFunction(() => {});
//=> false
.asyncGenerator(value)
is.asyncGenerator(
	(async function * () {
		yield 4;
	})()
);
//=> true

is.asyncGenerator(
	(function * () {
		yield 4;
	})()
);
//=> false
.asyncGeneratorFunction(value)
is.asyncGeneratorFunction(async function * () {
	yield 4;
});
//=> true

is.asyncGeneratorFunction(function * () {
	yield 4;
});
//=> false
.boundFunction(value)

Returns true for any bound function.

is.boundFunction(() => {});
//=> true

is.boundFunction(function () {}.bind(null));
//=> true

is.boundFunction(function () {});
//=> false
.map(value)
.set(value)
.weakMap(value)
.weakSet(value)
.weakRef(value)

Typed arrays

.int8Array(value)
.uint8Array(value)
.uint8ClampedArray(value)
.int16Array(value)
.uint16Array(value)
.int32Array(value)
.uint32Array(value)
.float32Array(value)
.float64Array(value)
.bigInt64Array(value)
.bigUint64Array(value)

Structured data

.arrayBuffer(value)
.sharedArrayBuffer(value)
.dataView(value)
.enumCase(value, enum)

TypeScript-only. Returns true if value is a member of enum.

enum Direction {
	Ascending = 'ascending',
	Descending = 'descending'
}

is.enumCase('ascending', Direction);
//=> true

is.enumCase('other', Direction);
//=> false

Emptiness

.emptyString(value)

Returns true if the value is a string and the .length is 0.

.emptyStringOrWhitespace(value)

Returns true if is.emptyString(value) or if it's a string that is all whitespace.

.nonEmptyString(value)

Returns true if the value is a string and the .length is more than 0.

.nonEmptyStringAndNotWhitespace(value)

Returns true if the value is a string that is not empty and not whitespace.

const values = ['property1', '', null, 'property2', '    ', undefined];

values.filter(is.nonEmptyStringAndNotWhitespace);
//=> ['property1', 'property2']
.emptyArray(value)

Returns true if the value is an Array and the .length is 0.

.nonEmptyArray(value)

Returns true if the value is an Array and the .length is more than 0.

.emptyObject(value)

Returns true if the value is an Object and Object.keys(value).length is 0.

Please note that Object.keys returns only own enumerable properties. Hence something like this can happen:

const object1 = {};

Object.defineProperty(object1, 'property1', {
	value: 42,
	writable: true,
	enumerable: false,
	configurable: true
});

is.emptyObject(object1);
//=> true
.nonEmptyObject(value)

Returns true if the value is an Object and Object.keys(value).length is more than 0.

.emptySet(value)

Returns true if the value is a Set and the .size is 0.

.nonEmptySet(Value)

Returns true if the value is a Set and the .size is more than 0.

.emptyMap(value)

Returns true if the value is a Map and the .size is 0.

.nonEmptyMap(value)

Returns true if the value is a Map and the .size is more than 0.

Miscellaneous

.directInstanceOf(value, class)

Returns true if value is a direct instance of class.

is.directInstanceOf(new Error(), Error);
//=> true

class UnicornError extends Error {}

is.directInstanceOf(new UnicornError(), Error);
//=> false
.urlInstance(value)

Returns true if value is an instance of the URL class.

const url = new URL('https://example.com');

is.urlInstance(url);
//=> true
.urlString(value)

Returns true if value is a URL string.

Note: this only does basic checking using the URL class constructor.

const url = 'https://example.com';

is.urlString(url);
//=> true

is.urlString(new URL(url));
//=> false
.truthy(value)

Returns true for all values that evaluate to true in a boolean context:

is.truthy('๐Ÿฆ„');
//=> true

is.truthy(undefined);
//=> false
.falsy(value)

Returns true if value is one of: false, 0, '', null, undefined, NaN.

.nan(value)
.nullOrUndefined(value)
.primitive(value)

JavaScript primitives are as follows:

  • null
  • undefined
  • string
  • number
  • boolean
  • symbol
  • bigint
.integer(value)
.safeInteger(value)

Returns true if value is a safe integer.

.plainObject(value)

An object is plain if it's created by either {}, new Object(), or Object.create(null).

.iterable(value)
.asyncIterable(value)
.class(value)

Returns true if the value is a class constructor.

.typedArray(value)
.arrayLike(value)

A value is array-like if it is not a function and has a value.length that is a safe integer greater than or equal to 0.

is.arrayLike(document.forms);
//=> true

function foo() {
	is.arrayLike(arguments);
	//=> true
}
foo();
.tupleLike(value, guards)

A value is tuple-like if it matches the provided guards array both in .length and in types.

is.tupleLike([1], [is.number]);
//=> true
function foo() {
	const tuple = [1, '2', true];
	if (is.tupleLike(tuple, [is.number, is.string, is.boolean])) {
		tuple // [number, string, boolean]
	}
}

foo();
.positiveNumber(value)

Check if value is a number and is more than 0.

.negativeNumber(value)

Check if value is a number and is less than 0.

.inRange(value, range)

Check if value (number) is in the given range. The range is an array of two values, lower bound and upper bound, in no specific order.

is.inRange(3, [0, 5]);
is.inRange(3, [5, 0]);
is.inRange(0, [-2, 2]);
.inRange(value, upperBound)

Check if value (number) is in the range of 0 to upperBound.

is.inRange(3, 10);
.htmlElement(value)

Returns true if value is an HTMLElement.

.nodeStream(value)

Returns true if value is a Node.js stream.

import fs from 'node:fs';

is.nodeStream(fs.createReadStream('unicorn.png'));
//=> true
.observable(value)

Returns true if value is an Observable.

import {Observable} from 'rxjs';

is.observable(new Observable());
//=> true
.infinite(value)

Check if value is Infinity or -Infinity.

.evenInteger(value)

Returns true if value is an even integer.

.oddInteger(value)

Returns true if value is an odd integer.

.propertyKey(value)

Returns true if value can be used as an object property key (either string, number, or symbol).

.formData(value)

Returns true if value is an instance of the FormData class.

const data = new FormData();

is.formData(data);
//=> true
.urlSearchParams(value)

Returns true if value is an instance of the URLSearchParams class.

const searchParams = new URLSearchParams();

is.urlSearchParams(searchParams);
//=> true
.any(predicate | predicate[], ...values)

Using a single predicate argument, returns true if any of the input values returns true in the predicate:

is.any(is.string, {}, true, '๐Ÿฆ„');
//=> true

is.any(is.boolean, 'unicorns', [], new Map());
//=> false

Using an array of predicate[], returns true if any of the input values returns true for any of the predicates provided in an array:

is.any([is.string, is.number], {}, true, '๐Ÿฆ„');
//=> true

is.any([is.boolean, is.number], 'unicorns', [], new Map());
//=> false
.all(predicate, ...values)

Returns true if all of the input values returns true in the predicate:

is.all(is.object, {}, new Map(), new Set());
//=> true

is.all(is.string, '๐Ÿฆ„', [], 'unicorns');
//=> false
.validDate(value)

Returns true if the value is a valid date.

All Date objects have an internal timestamp value which is the number of milliseconds since the Unix epoch. When a new Date is constructed with bad inputs, no error is thrown. Instead, a new Date object is returned. But the internal timestamp value is set to NaN, which is an 'Invalid Date'. Bad inputs can be an non-parsable date string, a non-numeric value or a number that is outside of the expected range for a date value.

const valid = new Date('2000-01-01');

is.date(valid);
//=> true
valid.getTime();
//=> 946684800000
valid.toUTCString();
//=> 'Sat, 01 Jan 2000 00:00:00 GMT'
is.validDate(valid);
//=> true

const invalid = new Date('Not a parsable date string');

is.date(invalid);
//=> true
invalid.getTime();
//=> NaN
invalid.toUTCString();
//=> 'Invalid Date'
is.validDate(invalid);
//=> false
.validLength(value)

Returns true if the value is a safe integer that is greater than or equal to zero.

This can be useful to confirm that a value is a valid count of something, ie. 0 or more.

.whitespaceString(value)

Returns true if the value is a string with only whitespace characters.

Type guards

When using is together with TypeScript, type guards are being used extensively to infer the correct type inside if-else statements.

import is from '@sindresorhus/is';

const padLeft = (value: string, padding: string | number) => {
	if (is.number(padding)) {
		// `padding` is typed as `number`
		return Array(padding + 1).join(' ') + value;
	}

	if (is.string(padding)) {
		// `padding` is typed as `string`
		return padding + value;
	}

	throw new TypeError(`Expected 'padding' to be of type 'string' or 'number', got '${is(padding)}'.`);
}

padLeft('๐Ÿฆ„', 3);
//=> '   ๐Ÿฆ„'

padLeft('๐Ÿฆ„', '๐ŸŒˆ');
//=> '๐ŸŒˆ๐Ÿฆ„'

Type assertions

The type guards are also available as type assertions, which throw an error for unexpected types. It is a convenient one-line version of the often repetitive "if-not-expected-type-throw" pattern.

import {assert} from '@sindresorhus/is';

const handleMovieRatingApiResponse = (response: unknown) => {
	assert.plainObject(response);
	// `response` is now typed as a plain `object` with `unknown` properties.

	assert.number(response.rating);
	// `response.rating` is now typed as a `number`.

	assert.string(response.title);
	// `response.title` is now typed as a `string`.

	return `${response.title} (${response.rating * 10})`;
};

handleMovieRatingApiResponse({rating: 0.87, title: 'The Matrix'});
//=> 'The Matrix (8.7)'

// This throws an error.
handleMovieRatingApiResponse({rating: '๐Ÿฆ„'});

Generic type parameters

The type guards and type assertions are aware of generic type parameters, such as Promise<T> and Map<Key, Value>. The default is unknown for most cases, since is cannot check them at runtime. If the generic type is known at compile-time, either implicitly (inferred) or explicitly (provided), is propagates the type so it can be used later.

Use generic type parameters with caution. They are only checked by the TypeScript compiler, and not checked by is at runtime. This can lead to unexpected behavior, where the generic type is assumed at compile-time, but actually is something completely different at runtime. It is best to use unknown (default) and type-check the value of the generic type parameter at runtime with is or assert.

import {assert} from '@sindresorhus/is';

async function badNumberAssumption(input: unknown) {
	// Bad assumption about the generic type parameter fools the compile-time type system.
	assert.promise<number>(input);
	// `input` is a `Promise` but only assumed to be `Promise<number>`.

	const resolved = await input;
	// `resolved` is typed as `number` but was not actually checked at runtime.

	// Multiplication will return NaN if the input promise did not actually contain a number.
	return 2 * resolved;
}

async function goodNumberAssertion(input: unknown) {
	assert.promise(input);
	// `input` is typed as `Promise<unknown>`

	const resolved = await input;
	// `resolved` is typed as `unknown`

	assert.number(resolved);
	// `resolved` is typed as `number`

	// Uses runtime checks so only numbers will reach the multiplication.
	return 2 * resolved;
}

badNumberAssumption(Promise.resolve('An unexpected string'));
//=> NaN

// This correctly throws an error because of the unexpected string value.
goodNumberAssertion(Promise.resolve('An unexpected string'));

FAQ

Why yet another type checking module?

There are hundreds of type checking modules on npm, unfortunately, I couldn't find any that fit my needs:

  • Includes both type methods and ability to get the type
  • Types of primitives returned as lowercase and object types as camelcase
  • Covers all built-ins
  • Unsurprising behavior
  • Well-maintained
  • Comprehensive test suite

For the ones I found, pick 3 of these.

The most common mistakes I noticed in these modules was using instanceof for type checking, forgetting that functions are objects, and omitting symbol as a primitive.

Why not just use instanceof instead of this package?

instanceof does not work correctly for all types and it does not work across realms. Examples of realms are iframes, windows, web workers, and the vm module in Node.js.

Related

Maintainers

is's People

Contributors

arfatsalman avatar arnovsky avatar arturovt avatar bigbigdreamer avatar bjornstar avatar brandon93s avatar ehmicky avatar eugene-mohc avatar itaisteinherz avatar joelpurra avatar kodie avatar ltetzlaff avatar marlun78 avatar melvin0008 avatar myfeetarefreezing avatar papb avatar popgoesthewza avatar richienb avatar rocktimsaikia avatar samverschueren avatar schneideror avatar scraggo avatar sdgluck avatar sdotson avatar simpod avatar sindresorhus avatar vladfrangu avatar wdzeng avatar xananax avatar zshannon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

is's Issues

Importing this module mutates global Symbol.observable

This module imports symbol-observable, which patches global Symbol.observable.
I just spent half an hour tracking down a bug which was caused by this - rxjs uses and checks for the presence of either Symbol.observable (if available) or of "@@observable". If RxJS was imported first and some Observable created, it would receive the "@@observable" shim. If then this module is imported, it mutates Symbol.observable. If then some dependency imports a different version of RxJS, it receives the Symbol.observable, and Rx from() is unable to recognize the Observable as an Observable.

Add `is.formData()`

From Got:

export default (body: unknown): body is FormData => is.nodeStream(body) && is.function_((body as FormData).getBoundary);

Any value in `is.numericValue` or similar?

At the moment, is.number returns true if the passed value is NaN. I'd quite like a function that returned true iff the passed value was a number with a real numeric value (0, -0, +0, etc. still count, Infinity I'd take either way (arguably true as Infinity is a real numeric value, just not actually countable)).

Not having yet thought about any edge cases, I imagine this would be a simple function:

export const numericValue = (value) => number(value) && ! nan(value)

`directInstanceOf()` method

Sometimes it's useful to be able to check if something is a direct instance of a class. instanceOf also matches any subclasses of that type, which is not always desirable.

const directInstanceOf  = (instance, klass) => Object.getPrototypeOf(instance) === klass.prototype;

It's not a lot of code, but I always forget how to do it properly, so would be nice to have a check for this.

Fix `.even()`/`.odd()` checks

I think those method names should be more explicit. Currently, they check if a number is an integer and whether it's even or odd. The problem is that a float can also be even or odd.

We should either:

  1. Rename them to .evenInteger() / .oddInteger().
  2. Remove the integer check and rename them to .evenNumber() / .oddNumber().

I'm leaning towards the former as I don't really see the use-case for floats for this, but I'm open to feedback.

Meta: principles for accepting new function proposals

It could be useful to expand in the FAQ or add a CONTRIBUTING.md stating what the principles are for deciding future function proposals. e.g. if the project's intention is to be strict, reasons to reject might include:

  • The alternative code it's replacing reads nicely anyway
  • It can be composed of two existing functions
  • It's just the negation of an existing function

Or perhaps you even consider it mostly feature-complete and prefer not to "bloat" it with many new functions?

On the other hand we're usually talking about one-liners with negligible bloat or maintenance burden, so rules under a flexible approach might be:

  • Unsurprising
  • Unlikely to result in confusion

Add `is.url()`

Continuing the discussion over at #73, we could add another method named is.url that detects if a given value is either a string URL or a URL instance:

const url = (value: unknown) => urlString(value) || urlInstance(value);

Add "asserts" variants of type guards

A new typescript language feature is slated for the v3.7.0 milestone: asserts. I think adding new asserts value is T variants of the type guard-enabled functions in is would be very useful. It would reduce the often repetitive "if-not-typeof-throw" pattern to a single line, while narrowing types.

Example implementation:

is.assertedString = (value: unknown): asserts value is string {
  if (!is.string(value)) {
    throw new TypeError("Not a string.");
  }
}
Without asserts:
function f(input: unknown) {
  if (!is.string(input)) {
    throw new TypeError("Not a string.");
  }
  // input has type string here.
}

With asserts:

function f(input: unknown) {
  is.assertedString(input);
  // input has type string here.
}

Function naming to be discussed.

npm install fail

log verobse:
node: 9.2.0
npm: 5.5.1
(used nvm)

`npm info it worked if it ends with ok
npm verb cli [ '/Users/xxxx/.nvm/versions/node/v9.2.0/bin/node',
npm verb cli '/Users/xxxx/.nvm/versions/node/v9.2.0/bin/npm',
npm verb cli 'install',
npm verb cli '-dd',
npm verb cli '@sindresorhus/is' ]
npm info using [email protected]
npm info using [email protected]
npm verb npm-session 50f73340ea9751c4
npm http fetch GET 404 https://registry.npmjs.org/@sindresorhus%2fis 1521ms
npm verb stack Error: 404 Not Found: @sindresorhus/is@latest
npm verb stack at fetch.then.res (/Users/xxxx/.nvm/versions/node/v9.2.0/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/fetch.js:42:19)
npm verb stack at tryCatcher (/Users/xxxx/.nvm/versions/node/v9.2.0/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
npm verb stack at Promise._settlePromiseFromHandler (/Users/xxxx/.nvm/versions/node/v9.2.0/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:512:31)
npm verb stack at Promise._settlePromise (/Users/xxxx/.nvm/versions/node/v9.2.0/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:569:18)
npm verb stack at Promise._settlePromise0 (/Users/xxxx/.nvm/versions/node/v9.2.0/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:614:10)
npm verb stack at Promise._settlePromises (/Users/xxxx/.nvm/versions/node/v9.2.0/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:693:18)
npm verb stack at Async._drainQueue (/Users/xxxx/.nvm/versions/node/v9.2.0/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:133:16)
npm verb stack at Async._drainQueues (/Users/xxxx/.nvm/versions/node/v9.2.0/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:143:10)
npm verb stack at Immediate.Async.drainQueues [as _onImmediate] (/Users/xxxx/.nvm/versions/node/v9.2.0/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:17:14)
npm verb stack at runCallback (timers.js:800:20)
npm verb stack at tryOnImmediate (timers.js:762:5)
npm verb stack at processImmediate [as _immediateCallback] (timers.js:733:5)
npm verb cwd /Users/xxxx/workspace/lego-web
npm verb Darwin 17.2.0
npm verb argv "/Users/xxxx/.nvm/versions/node/v9.2.0/bin/node" "/Users/xxxx/.nvm/versions/node/v9.2.0/bin/npm" "install" "-dd" "@sindresorhus/is"
npm verb node v9.2.0
npm verb npm v5.5.1
npm ERR! code E404
npm ERR! 404 Not Found: @sindresorhus/is@latest
npm verb exit [ 1, true ]

npm ERR! A complete log of this run can be found in:
npm ERR! /Users/xxxx/.npm/_logs/2018-04-12T07_47_49_725Z-debug.log
`

`is.urlString()`

Since checking if a given value is a valid URL is quite common, I think having a method such a method in is would be very useful (this could be done using is-url-superb).

I'm not sure if this directly aligns with the goals of the module, as a URL isn't really a data structure / type / object, but this method will still be useful in many cases. Also, one could argue that you could just use is-url-superb directly, but having this method in is would still be a good addition.

is.defined

Would you support a PR for is.defined? Clearer logic in downstream code than !is.undefined

Package is not available on NPM registry

Please investigate the issue with the package not resolving on npmjs.org.

Example,

> yarn add @sindresorhus/is

yarn add v1.0.2
[1/4] Resolving packages...
error An unexpected error occurred: "https://registry.yarnpkg.com/@sindresorhus%2fis: Not Found".

Same with npm,

> npm i @sindresorhus/is

npm ERR! code E404
npm ERR! 404 Not Found: @sindresorhus/is@latest
> node -v
v9.10.1
> npm -v
5.8.0
> yarn -v
1.0.2

is there any reason for `is.sharedArrayBuffer` special condition?

I'm doing a pull request to remove code repetition, and the sharedArrayBuffer method bothers me.

is.sharedArrayBuffer = x => {
	try {
		return getObjectType(x) === 'SharedArrayBuffer';
	} catch (err) {
		return false;
	}
};

Part of the pull request is making a method called isTypeOf (WIP, may change after review),

which is:

const getObjectType = x => toString.call(x).slice(8, -1);
const isTypeOf = type => x => getObjectType(x) === type;

and the usage looks like:

is.float32Array = isTypeOf('Float32Array');
is.float64Array = isTypeOf('Float64Array');

is.arrayBuffer = isTypeOf('ArrayBuffer');

whereas currently there's a getObjectType(x) === 'some type' repetition throughout the code.

What's the reason for sharedArrayBuffers special check?

Ideas

I'm gonna try hard not to go overboard with stuff I will never need, but just a quick brain dump:

  • .withinRange(3, [0, 5])
  • .generator()
  • .domElement()
  • .generatorFunction()
  • .infinity() (Would match Infinity and -Infinity) (Maybe .infinite() would be a better name?)
  • .empty([]) (string, array, object, map, set, ...)
  • .blob()
  • .asyncFunction()
  • And .any()/.all() methods to match multiple types.

Feedback wanted! ๐Ÿ˜€

Encountered compilation errors related to SharedArrayBuffer

When using @sindresorhus/is@^0.9.0, I am encountering the following error message when compiling TypeScript code that imports the module:

[...]$ tsc
node_modules/@sindresorhus/is/dist/index.d.ts:81:55 - error TS2304: Cannot find name 'SharedArrayBuffer'.

81     const sharedArrayBuffer: (value: any) => value is SharedArrayBuffer;

The following are all of the relevant files in the workspace.

package.json

{
  "name": "temp",
  "version": "1.0.0",
  "license": "Apache-2.0",
  "devDependencies": {
    "@types/node": "^10.1.2",
    "typescript": "^2.8.3"
  },
  "dependencies": {
    "@sindresorhus/is": "^0.9.0"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "declaration": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "lib": ["es2016"],
    "module": "commonjs",
    "noEmitOnError": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "pretty": true,
    "sourceMap": true,
    "strict": true,
    "target": "es2016",
    "rootDir": ".",
    "outDir": "build"
  },
  "include": [
    "src/*.ts",
    "src/**/*.ts",
    "test/*.ts",
    "test/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

src/index.ts

import is from '@sindresorhus/is';

Feature request: duck typing

In some cases is.instanceof doesn't work and we need to use duck typing.

Something like

is.equivalent(objectBeingTested, [members, to, look, for]): boolean;

Used like this:

if (!is.equivalent(myAnimal, [Animal.name, Animal.species, Animal.size]))
  throw Error("Not an animal!");

I'm not sure what is the best method signature, but you get the idea.

I'm also not sure what is the best name, is.equivalent() is maybe incorrect as that implies testing two objects that are fully equivalent. Maybe something like is.duckTypeof(), is.duckType(), is.ducktype().

[Question] Works on frontend?

I'm using this on the server side and it's great (and thank you very much! ๐Ÿ‘).

I tried to use it in on the client side (angular) but my app won't compile because

Module not found: Error: Can't resolve 'url' in '......./node_modules/@sindresorhus/is/dist'

And I found this in the module:

// TODO: Use the `URL` global when targeting Node.js 10
// tslint:disable-next-line
const URLGlobal = typeof URL === 'undefined' ? require('url').URL : URL;

Is there a way to use this on the frontend, or is that impossible? The docs didn't say that I can't use it on the frontend, so I wasn't sure. If the only thing stopping its use on the frontend is the url module, maybe there is a way to workaround that?

`is.numericString()`

Sometimes I need to check if a string is a valid number. I guess we could just do !Number.isNaN(Number(string));

Use TypeScript

I think that re-writing the code in typescript could really help this library, for the following reasons -

  1. This will make it easy to integrate into typescript based codebases
  2. This will help with readability and maintenance of the code
  3. This will allow us to use the newest JS/TS features, while keeping compatibility with older Node versions

Think about the inRange pull-request - we could not use array destructuring because this messed up compatibility with Node v4.
If we write this in typescript, the compiled js will be compatible with older versions, while the source code will be written with every JS feature we see fit.

npm i fails

npm version 5.6.0
node version 8.9.4
os windows 7

0 info it worked if it ends with ok
1 verbose cli [ 'C:\Program Files\nodejs\node.exe',
1 verbose cli 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js',
1 verbose cli 'i',
1 verbose cli '-g',
1 verbose cli '@sindresorhus/[email protected]' ]
2 info using [email protected]
3 info using [email protected]
4 verbose npm-session 614da0fd333ea933
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 http fetch GET 404 https://registry.npmjs.org/@sindresorhus%2fis 839ms
8 silly fetchPackageMetaData error for @sindresorhus/[email protected] 404 Not Found: @sindresorhus/[email protected]
9 verbose stack Error: 404 Not Found: @sindresorhus/[email protected]
9 verbose stack at fetch.then.res (C:\Program Files\nodejs\node_modules\npm\node_modules\pacote\lib\fetchers\registry\fetch.js:42:19)
9 verbose stack at tryCatcher (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\util.js:16:23)
9 verbose stack at Promise._settlePromiseFromHandler (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:512:31)
9 verbose stack at Promise._settlePromise (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:569:18)
9 verbose stack at Promise._settlePromise0 (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:614:10)
9 verbose stack at Promise._settlePromises (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\promise.js:693:18)
9 verbose stack at Async._drainQueue (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:133:16)
9 verbose stack at Async._drainQueues (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:143:10)
9 verbose stack at Immediate.Async.drainQueues (C:\Program Files\nodejs\node_modules\npm\node_modules\bluebird\js\release\async.js:17:14)
9 verbose stack at runCallback (timers.js:789:20)
9 verbose stack at tryOnImmediate (timers.js:751:5)
9 verbose stack at processImmediate [as _immediateCallback] (timers.js:722:5)
10 verbose cwd D:\dev
11 verbose Windows_NT 6.1.7601
12 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "i" "-g" "@sindresorhus/[email protected]"
13 verbose node v8.9.4
14 verbose npm v5.6.0
15 error code E404
16 error 404 Not Found: @sindresorhus/[email protected]
17 verbose exit [ 1, true ]

Add a test for `assert.any([...], ...)`

Given

assert.any([is.boolean, is.undefined], options.decompress);

TypeScript throws:

Argument of type '(((value: unknown) => value is boolean) | ((value: unknown) => value is undefined))[]' is not assignable to parameter of type 'Predicate'.
  Type '(((value: unknown) => value is boolean) | ((value: unknown) => value is undefined))[]' provides no match for the signature '(value: unknown): boolean'.

feature request: `oneOf` that allows you to check a value against multiple predicates

Similar to #95, but this is more of a feature request: .oneOf method that allows you to check a value against multiple predicates.

I've implemented it by doing the following:

is.oneOf = (item, predicatesArray) => {
  return predicatesArray.some(predicate => predicate(item));
}

To use it:

it("uses is predicates for a true match", () => {
      expect(is.oneOf("hi", [is.function, is.string, is.object])).toEqual(true);
    });

How do you check if a value is of any generic type?

I'd like to do something like this:

class Foo {}
class Bar {}

is(value, [Foo, Bar])

How do I use this library to check that the value is one of a given type, or the simpler (if I need to abstract it:

is(value, Foo)

Does this library only support built-in JavaScript primitives / objects?

`is.version()`

This might be a bit of an edge-case, but having a method which checks if a given string is a valid version number is useful in some cases. This could be implemented similarly to the way isValidVersion is in np:

const semver = require('semver');
const isValidVersion = input => Boolean(semver.valid(input));

This would require us to add the semver dependency, though.

`is(promise)` returns `Object` on Node.js 4

While is.promise(promise) works across all Node.js versions, just doing is(promise) doesn't. The difference is that we check if it has a then and a catch method in the former.

In Node.js 4 toString.call(promise) returns [object Object] which differs from newer versions where it returns the correct type.

Improve type guard for `.all`

Issuehunt badges

It would be nice if this worked:

const a = foo();
const b = bar();

// Both `a` and `b` is an `object`, but TS only knows they're `any`.

if (is.all(is.object, a, b)) {
	// `a` and `b` is now known by TS as `object`
}

There is a $30.00 open bounty on this issue. Add more on Issuehunt.

`is.asyncIterable()` method

Something like:

typeof Symbol.asyncIterator !== 'undefined' && typeof value[Symbol.asyncIterator] === 'function'

No TypeScript intellisense possible with the current index.d.ts

Hi,

I use is actively since almost one year and i still have no type inference (TypeScript intellisense) on Visual Studio Code with the package.

So i decided to take a look at the index.d.ts in /dist and found a couple of problems.

For me, only the function is should be exported and everything else should be member of the namespace is. (Even after correction, method like is.string feel more like properties than real methods).

TypeScript def:
/// <reference types="node" />
declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array;
declare type Primitive = null | undefined | string | number | boolean | Symbol;

declare type DomElement = object & {
    nodeType: 1;
    nodeName: string;
};
declare type NodeStream = object & {
    pipe: Function;
};

declare function is(value: any): is.TypeName;
declare namespace is {

    export interface ArrayLike {
        length: number;
    }
    export interface Class<T = any> {
        new (...args: any[]): T;
    }

    export const undefined: (value: any) => value is undefined;
    export const string: (value: any) => value is string;
    export const number: (value: any) => value is number;
    export const function_: (value: any) => value is Function;
    export const null_: (value: any) => value is null;
    export const class_: (value: any) => value is Class<any>;
    export const boolean: (value: any) => value is boolean;
    export const symbol: (value: any) => value is Symbol;
    export const array: (arg: any) => arg is any[];
    export const buffer: (obj: any) => obj is Buffer;
    export const nullOrUndefined: (value: any) => value is null | undefined;
    export const object: (value: any) => value is object;
    export const iterable: (value: any) => value is IterableIterator<any>;
    export const asyncIterable: (value: any) => value is AsyncIterableIterator<any>;
    export const generator: (value: any) => value is Generator;
    export const nativePromise: (value: any) => value is Promise<any>;
    export const promise: (value: any) => value is Promise<any>;
    export const generatorFunction: (value: any) => value is GeneratorFunction;
    export const asyncFunction: (value: any) => value is Function;
    export const boundFunction: (value: any) => value is Function;
    export const regExp: (value: any) => value is RegExp;
    export const date: (value: any) => value is Date;
    export const error: (value: any) => value is Error;
    export const map: (value: any) => value is Map<any, any>;
    export const set: (value: any) => value is Set<any>;
    export const weakMap: (value: any) => value is WeakMap<any, any>;
    export const weakSet: (value: any) => value is WeakSet<any>;
    export const int8Array: (value: any) => value is Int8Array;
    export const uint8Array: (value: any) => value is Uint8Array;
    export const uint8ClampedArray: (value: any) => value is Uint8ClampedArray;
    export const int16Array: (value: any) => value is Int16Array;
    export const uint16Array: (value: any) => value is Uint16Array;
    export const int32Array: (value: any) => value is Int32Array;
    export const uint32Array: (value: any) => value is Uint32Array;
    export const float32Array: (value: any) => value is Float32Array;
    export const float64Array: (value: any) => value is Float64Array;
    export const arrayBuffer: (value: any) => value is ArrayBuffer;
    export const sharedArrayBuffer: (value: any) => value is SharedArrayBuffer;
    export const dataView: (value: any) => value is DataView;
    export const directInstanceOf: <T>(instance: any, klass: Class<T>) => instance is T;
    export const urlInstance: (value: any) => value is URL;
    export const truthy: (value: any) => boolean;
    export const falsy: (value: any) => boolean;
    export const nan: (value: any) => boolean;
    export const primitive: (value: any) => value is Primitive;
    export const integer: (value: any) => value is number;
    export const safeInteger: (value: any) => value is number;
    export const plainObject: (value: any) => boolean;
    export const typedArray: (value: any) => value is TypedArray;
    export const arrayLike: (value: any) => value is ArrayLike;
    export const inRange: (value: number, range: number | number[]) => boolean;
    export const domElement: (value: any) => value is DomElement;
    export const observable: (value: any) => boolean;
    export const nodeStream: (value: any) => value is NodeStream;
    export const infinite: (value: any) => boolean;
    export const even: (rem: number) => boolean;
    export const odd: (rem: number) => boolean;
    export const empty: (value: any) => boolean;
    export const emptyOrWhitespace: (value: any) => boolean;
    export const any: (predicate: any, ...values: any[]) => any;
    export const all: (predicate: any, ...values: any[]) => any;

    export const enum TypeName {
        null = "null",
        boolean = "boolean",
        undefined = "undefined",
        string = "string",
        number = "number",
        symbol = "symbol",
        Function = "Function",
        GeneratorFunction = "GeneratorFunction",
        AsyncFunction = "AsyncFunction",
        Observable = "Observable",
        Array = "Array",
        Buffer = "Buffer",
        Object = "Object",
        RegExp = "RegExp",
        Date = "Date",
        Error = "Error",
        Map = "Map",
        Set = "Set",
        WeakMap = "WeakMap",
        WeakSet = "WeakSet",
        Int8Array = "Int8Array",
        Uint8Array = "Uint8Array",
        Uint8ClampedArray = "Uint8ClampedArray",
        Int16Array = "Int16Array",
        Uint16Array = "Uint16Array",
        Int32Array = "Int32Array",
        Uint32Array = "Uint32Array",
        Float32Array = "Float32Array",
        Float64Array = "Float64Array",
        ArrayBuffer = "ArrayBuffer",
        SharedArrayBuffer = "SharedArrayBuffer",
        DataView = "DataView",
        Promise = "Promise",
        URL = "URL"
    }
}
export as namespace is;
export = is;

I wanted to see the subject with you before opening any pull-request !

Best Regards,
Thomas

is(value) is not slightly tested

Issuehunt badges

There are no tests that is(value) works correctly.

This makes it hard to make changes for it, f.e replace all the primitive if checks with

if (is.primitive(value)) {
   return typeof value;
}

I had an idea regarding the testType method.
Currently, it accepts an optional argument that is an array (excludes).

I played with the method a bit, and it looks something like this:

const testTypeName = (t, fixture, typename) => {
	t.is(m(fixture), typename, `Type name of ${util.inspect(fixture)} is not ${typename}`);
};

// This ensure a certain method matches only the types
// it's supposed to and none of the other methods' types
const testType = (t, type, {exclude, typename} = {}) => {
	for (const [key, value] of types) {
		// TODO: Automatically exclude value types in other tests that we have in the current one.
		// Could reduce the use of `exclude`.
		if (exclude && exclude.indexOf(key) !== -1) {
			continue;
		}

		const assert = key === type ? t.true.bind(t) : t.false.bind(t);
		const is = m[type];
		const fixtures = Array.isArray(value) ? value : [value];

		for (const fixture of fixtures) {
			assert(is(fixture), `Value ${util.inspect(fixture)} is not ${type}`);

			if (typename) {
				testTypeName(t, fixture, typename);
			}
		}
	}
};

basically the third parameter becomes an object with which we can pass optional parameters.

tests with excludes now look like:

test('is.undefined', t => {
	testType(t, 'undefined', {
		exclude: ['nullOrUndefined'],
		typename: 'undefined'
	});
});

test('is.null', t => {
	testType(t, 'null', {
		exclude: ['nullOrUndefined'],
		typename: 'null'
	});
});

See that I can easily pass data(typename) for checking is(null) === 'null'), and just not pass it if I don't want to check it.

This also allows the tests to be a little more verbose (you explicitly say that you exclude those types from the test).

mrhen earned $30.00 by resolving this issue!

Runtime errors if compiled with `"esModuleInterop": false`

Thanks for the lovely library! With version 0.17.0, we noticed that our tests suddenly weren't passing:
googleapis/nodejs-pubsub#591

Using TypeScript, everything compiles fine - then we'd get this at runtime:

const iss = is_1.default.string('๐Ÿ‘‹');
                         ^

TypeError: Cannot read property 'string' of undefined
    at Object.<anonymous> (/Users/beckwith/Code/isbroke/build/src/index.js:4:26)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
    at internal/main/run_main_module.js:21:11

I have a minimal repo here:
https://github.com/JustinBeckwith/is-broke

Just clone, npm install, and npm start to see the error. One thing to note - we do not have esModuleInterop enabled in our tsconfig. If I set that to true - everything does seem to work.

We found that setting esModuleInterop in our modules could have downstream effects for other users (like this case), so we keep it off. I noticed that your base level tsconfig enables both synthetic default imports and es module interop:
https://github.com/sindresorhus/tsconfig/blob/master/tsconfig.json#L9

TL;DR: I think the answer here is to disable esModuleInterop as a default configuration for your TypeScript modules. Could be wrong ๐Ÿคทโ€โ™‚

Browser support?

Does this library support usage in a browser?

It seems that since it imports util and outputs es2016 code to NPM the answer is no. I didn't see anything clearly stating Node-only in the readme though.

If the answer is no, would you accept a PR that made it browser-compliant? It doesn't seem like the changes would be significant.

Thanks,

Sam

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.