Essential utilities for TypeScript projects
Ideas for additional essential utilities welcome. Type-only utilities belong in type-fest.
npm install ts-extrasRequires TypeScript >=6 and {exactOptionalPropertyTypes: true} in your tsconfig. Disabling it is unsupported.
import {isDefined} from 'ts-extras';
[1, undefined, 2].filter(isDefined);
//=> [1, 2]General
asWritable- Cast the given value to beWritable.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 keysobjectKeys()reports for a value of the given type.
Type guard
isDefined- Check whether a value is defined, meaning it is notundefined.isPresent- Check whether a value is present (non-nullable), meaning it is neithernullnorundefined.isPropertyDefined- Check whether a specific own property of a value is defined, meaning it is notundefined.isPropertyPresent- Check whether a specific own property of a value is present (non-nullable), meaning it is neithernullnorundefined.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 notundefined.assertPresent- Assert that the given value is present (non-nullable), meaning it is neithernullnorundefined.assertError- Assert that the given value is anError.assertNever- Assert that a code path is unreachable.
Improved builtin
arrayAt- A strongly-typed version ofArray#at()with improved tuple support (supports-1and positive literal indices for tuples).arrayConcat- A strongly-typed version ofArray#concat()that properly handles arrays of different types.arrayJoin- A strongly-typed version ofArray#join()that preserves literal string types.arrayFirst- Return the first item of an array with stronger typing for tuples.arrayIncludes- A strongly-typed version ofArray#includes()that properly acts as a type guard.arrayIndexOf- A strongly-typed version ofArray#indexOf()that accepts an item wider than the array's element type.arrayIsArray- A strongly-typed version ofArray.isArray().arrayLast- Return the last item of an array with stronger typing for tuples.arrayLastIndexOf- A strongly-typed version ofArray#lastIndexOf()that accepts an item wider than the array's element type.isFinite- A strongly-typed version ofNumber.isFinite().isInteger- A strongly-typed version ofNumber.isInteger().isSafeInteger- A strongly-typed version ofNumber.isSafeInteger().objectAssign- A strongly-typed version ofObject.assign().objectKeys- A strongly-typed version ofObject.keys().objectValues- A strongly-typed version ofObject.values().objectEntries- A strongly-typed version ofObject.entries().objectFromEntries- A strongly-typed version ofObject.fromEntries().objectMapValues- Map over an object's values while keeping the result's keys strongly typed.objectHasOwn- A strongly-typed version ofObject.hasOwn()that narrows the object type.mapHas- A strongly-typed version ofMap#has()that properly acts as a type guard.setHas- A strongly-typed version ofSet#has()that properly acts as a type guard.stringSplit- A strongly-typed version ofString#split()that returns a tuple for literal strings.stringStartsWith- A strongly-typed version ofString#startsWith()that narrows the string to a template literal type.stringEndsWith- A strongly-typed version ofString#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.
These functions solve different problems despite all checking property existence:
keyIn - Key narrowing for union types:
- Uses the
inoperator, 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
keyofthe 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__andconstructorfor security
objectHasIn - Object narrowing with prototype chain:
- Uses the
inoperator, 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 theinoperator 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
Recordtype, so both branches remain usable - Best for: "Can I safely access this property (including inherited)?"
- Guards against
__proto__andconstructorfor security
objectHasOwn - Object narrowing for own properties:
- Uses
Object.hasOwn(), checking only own properties, and answersfalserather than throwing fornullandundefined - Narrows the object type to include the checked property, including unions and nullable values, like the
inoperator 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
Recordtype, 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
elsebranch typednever - 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)
}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.
- type-fest - A collection of essential TypeScript types
- eslint-plugin-typefest - ESLint plugin that encourages consistent usage of
type-festandts-extras - is - Type guards for any situation
- camelcase-keys - Runtime transformation of object properties to camel-case (like
type-fest'sCamelCasedPropertiesDeep)