Skip to content
sindresorhusPublic

About

Essential utilities for TypeScript projects

Resources

Code of conduct

Contributing

Stars

824 stars

Watchers

3 watching

Forks

Repository files navigation

ts-extras npm dependents npm downloads

Essential utilities for TypeScript projects

Ideas for additional essential utilities welcome. Type-only utilities belong in type-fest.

Install

npm install ts-extras

Requires TypeScript >=6 and {exactOptionalPropertyTypes: true} in your tsconfig. Disabling it is unsupported.

Usage

import {isDefined} from 'ts-extras';

[1, undefined, 2].filter(isDefined);
//=> [1, 2]

API

General

  • asWritable - Cast the given value to be Writable.
  • objectUpdate - Apply a type-checked partial update to an object in place.
  • isEqualType - Check if two types are equal at compile time.
  • safeCastTo - Constrain a value to the given type safely.
  • ObjectKeys - The keys objectKeys() reports for a value of the given type.

Type guard

  • isDefined - Check whether a value is defined, meaning it is not undefined.
  • isPresent - Check whether a value is present (non-nullable), meaning it is neither null nor undefined.
  • isPropertyDefined - Check whether a specific own property of a value is defined, meaning it is not undefined.
  • isPropertyPresent - Check whether a specific own property of a value is present (non-nullable), meaning it is neither null nor undefined.
  • isEmpty - Check whether an array is empty.
  • isNonEmpty - Check whether an array has at least one element.
  • hasAtLeast - Check whether an array has at least the given number of elements.
  • isTruthy - Check whether a value is truthy. Use it as a type guard in .filter().
  • isInfinite - Check whether a value is infinite.
  • keyIn - Check if a key is in an object and narrow the key to the object's keys.
  • not - Invert a type predicate function.
  • objectHasIn - Check if an object has a property (including inherited) and narrow the object type.
  • assert - Assert that the given condition is truthy.
  • assertDefined - Assert that the given value is defined, meaning it is not undefined.
  • assertPresent - Assert that the given value is present (non-nullable), meaning it is neither null nor undefined.
  • assertError - Assert that the given value is an Error.
  • assertNever - Assert that a code path is unreachable.

Improved builtin

  • arrayAt - A strongly-typed version of Array#at() with improved tuple support (supports -1 and positive literal indices for tuples).
  • arrayConcat - A strongly-typed version of Array#concat() that properly handles arrays of different types.
  • arrayJoin - A strongly-typed version of Array#join() that preserves literal string types.
  • arrayFirst - Return the first item of an array with stronger typing for tuples.
  • arrayIncludes - A strongly-typed version of Array#includes() that properly acts as a type guard.
  • arrayIndexOf - A strongly-typed version of Array#indexOf() that accepts an item wider than the array's element type.
  • arrayIsArray - A strongly-typed version of Array.isArray().
  • arrayLast - Return the last item of an array with stronger typing for tuples.
  • arrayLastIndexOf - A strongly-typed version of Array#lastIndexOf() that accepts an item wider than the array's element type.
  • isFinite - A strongly-typed version of Number.isFinite().
  • isInteger - A strongly-typed version of Number.isInteger().
  • isSafeInteger - A strongly-typed version of Number.isSafeInteger().
  • objectAssign - A strongly-typed version of Object.assign().
  • objectKeys - A strongly-typed version of Object.keys().
  • objectValues - A strongly-typed version of Object.values().
  • objectEntries - A strongly-typed version of Object.entries().
  • objectFromEntries - A strongly-typed version of Object.fromEntries().
  • objectMapValues - Map over an object's values while keeping the result's keys strongly typed.
  • objectHasOwn - A strongly-typed version of Object.hasOwn() that narrows the object type.
  • mapHas - A strongly-typed version of Map#has() that properly acts as a type guard.
  • setHas - A strongly-typed version of Set#has() that properly acts as a type guard.
  • stringSplit - A strongly-typed version of String#split() that returns a tuple for literal strings.
  • stringStartsWith - A strongly-typed version of String#startsWith() that narrows the string to a template literal type.
  • stringEndsWith - A strongly-typed version of String#endsWith() that narrows the string to a template literal type.

isPropertyDefined, isPropertyPresent, and not narrow when passed directly to .filter(), such as items.filter(isPropertyDefined('value')). In an if/else, the property guards' else branch assumes that a declared property is an own data property, so a value whose property comes from an accessor or the prototype can reach a branch typed never, and so can a value checked with a union key, such as 'a' | 'b'. For not, an input member that only overlaps the guarded type can do the same.

FAQ

What is the difference between keyIn, objectHasIn, and objectHasOwn?

These functions solve different problems despite all checking property existence:

keyIn - Key narrowing for union types:

  • Uses the in operator, checking the prototype chain
  • Narrows a union of literal keys when every matching key is declared in every member of the object type
  • An optional key narrows too, but the false branch then also excludes it, even though it may be absent at runtime
  • Returns a boolean without narrowing for index signatures, keys present in only some union members, widened keys, opaque objects, and inherited names not declared in the object type
  • Key narrowing assumes that queried properties present at runtime appear in keyof the object's type. Extra own or custom-prototype properties hidden by a narrower type are unsupported for narrowing; the runtime check still finds them.
  • Best for: "Which of these possible keys actually exists?"
  • Guards against __proto__ and constructor for security

objectHasIn - Object narrowing with prototype chain:

  • Uses the in operator, checking the prototype chain
  • Narrows the object type to include the checked property, including unions such as {a: number} | {b: string} and nullable values such as {a: number} | null, like the in operator does
  • Returns a boolean without narrowing when an input member already satisfies the property proof without declaring the key as required, such as a widened key on a Record type, so both branches remain usable
  • Best for: "Can I safely access this property (including inherited)?"
  • Guards against __proto__ and constructor for security

objectHasOwn - Object narrowing for own properties:

  • Uses Object.hasOwn(), checking only own properties, and answers false rather than throwing for null and undefined
  • Narrows the object type to include the checked property, including unions and nullable values, like the in operator does
  • Returns a boolean without narrowing when an input member already satisfies the property proof without declaring the key as required, such as a widened key on a Record type, so both branches remain usable
  • Assumes a declared required property is own, so a property from the prototype, such as a class method, can reach an else branch typed never
  • Best for: "Can I safely access this own property on this object?"
import {keyIn, objectHasIn, objectHasOwn} from 'ts-extras';

// keyIn - narrows the key (prototype chain)
const object = {foo: 1, bar: 2};
const key = 'foo' as 'foo' | 'bar' | 'baz';
if (keyIn(object, key)) {
	// `key` is now: 'foo' | 'bar' (only existing keys)
	console.log(object[key]); // Safe
}

// Inherited names are checked at runtime, but are not guaranteed on an object with no prototype.
const maybeInherited = 'toString' as 'toString' | 'nope';
if (keyIn(object, maybeInherited)) {
	// `maybeInherited` remains: 'toString' | 'nope' in both branches
}

// objectHasIn - narrows the object (prototype chain)
const data: unknown = {foo: 1};
if (objectHasIn(data, 'toString')) {
	// `data` is now: Record<'toString', unknown>
	console.log(data.toString); // Safe (inherited method)
}

// objectHasOwn - narrows the object (own properties only)
if (objectHasOwn(data, 'foo')) {
	// `data` is now: Record<'foo', unknown>
	console.log(data.foo); // Safe (own property)
}

What is the difference between this and type-fest?

The type-fest package contains only types, meaning they are only used at compile-time and nothing is ever compiled into actual JavaScript code. This package contains functions that are compiled into JavaScript code and used at runtime.

Related

  • type-fest - A collection of essential TypeScript types
  • eslint-plugin-typefest - ESLint plugin that encourages consistent usage of type-fest and ts-extras
  • is - Type guards for any situation
  • camelcase-keys - Runtime transformation of object properties to camel-case (like type-fest's CamelCasedPropertiesDeep)

About

Essential utilities for TypeScript projects

Resources

Code of conduct

Contributing

Stars

824 stars

Watchers

3 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages