The Principal Dev – Masterclass for Tech Leads

The Principal Dev – Masterclass for Tech Leads28-29 May

Join

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

Usage

import {isDefined} from 'ts-extras';

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

API

General

Type guard

Improved builtin

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:

objectHasIn - Object narrowing with prototype chain:

objectHasOwn - Object narrowing for own properties:

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

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

// objectHasOwn - narrows the object (own properties only)
if (objectHasOwn(data, 'foo')) {
	// `data` is now: unknown & {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.

Join libs.tech

...and unlock some superpowers

GitHub

We won't share your data with anyone else.