Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

type-fns

ehmpathy3.9kMIT1.19.0TypeScript support: included

A set of types, type checks, and type guards for simpler, safer, and easier to read code.

types, type guards, guards, type checks, checks, type, checking, typescript

readme

type-fns

Narrow your codepaths with generic types, type checks, and type guards for simpler, safer, and easier to read code.

Purpose

Narrow your codepaths for simpler, safer, and easier to read code.

  • simplify your code paths with type narrowing using type checks (e.g., isPresent, isAPromise, isAFunction, isOfEnum, etc)
  • declare your types more readably with powerful extended types (e.g., PickOne, HasMetadata, etc)

This library is a collection of generic types, type guards, and type checks we've found the need to define over and over again across different domains, collected in one spot for reusability.

Background

Type guards are built from type checks, built on a type predicate.

  • type predicate: value is 'blue'
  • type check: const isBlue(value: any): value is 'blue' = value === 'blue'
  • type guard: if (isBlue(color)) throw new Error('should be blue')

Type guards allow us to to inform typescript we've checked the type of a variable at runtime, enabling type narrowing.

For more information about typescripts type guards, type checks, and type predicates, see this section in the typescript docs on "narrowing"

Install

npm install --save type-fns

Examples

generic types

PickOne

The generic type PickOne allows you to specify that only one of the keys in the object can be defined, the others must be undefined.

This is very useful when working with an interface where you have exclusive settings. For example:

import { PickOne } from 'type-fns';

const findWrench = async ({
  size,
}: {
  /**
   * specify the size of the wrench in either `imperial` or `metric` units
   *
   * note
   * - we "PickOne" because this is an exclusive option, a size cant be defined in both
   */
  size: PickOne<{
    metric: {
      millimeters: number,
    }
    imperial: {
      inches: string,
    }
  }>
}) => {
  // ...
}

// you can find by metric
await findWrench({
  size: {
    metric: { millimeters: 16 }
  }
})

// you can find by imperial
await findWrench({
  size: {
    imperial: { inches: '5/16' }
  }
})

// you can't find by both
await findWrench({
  size: {
    metric: { millimeters: 16 } , // 🛑 typescript error: `Type '{ millimeters: number; }' is not assignable to type 'undefined'.ts(2322)`
    imperial: { inches: '5/16' }
  }
})

DropFirst

The generic type DropFirst lets you exclude the first element of an array.

type NumberStringString = [number, string, string];
const numStrStr: NumberStringString = [1, '2', '3'];
const strStr: DropFirst<NumberStringString> = ['1', '2'];
const str: string = strStr[0];
const num: number = numStrStr[0];

Useful, for example, if you want to change the first parameter of a function while keeping the rest the same.

type guards

isPresent

The type predicate of isPresent any informs typescript that if a value passes this type check, the value is not null or undefined:

This is most useful for filtering, to inform typescript that we have removed all null or undefined values from an array. For example:

import { isPresent } from 'type-fns';

// you have an array that contains strings or nulls
const stringsOrNulls = ['success:1', 'success:2', null, 'success:3', null]; // type = `(string | null)[]`

// now you want to get rid of all the nulls and only think about the strings: use `isPresent`
const strings = stringsOrNulls.filter(isPresent); // type = string[]

// the type predicate on the `isPresent` function informs typescript that all of the nulls and undefineds have been removed
strings.map((string) => string.toUpperCase()); // now you can operate on the strings without typescript complaining!

isOfEnum

The type predicate of isOfEnum allows you to check whether a value is a valid member of an enum. For example:

import { createIsOfEnum } from 'type-fns';

// you have an enum
enum Planet {
  ...
  VENUS = 'VENUS',
  EARTH = 'EARTH',
  MARS = 'MARS',
  ...
}

// define a type check for your enum
const isPlanet = createIsOfEnum(Planet);

// use your new type check for a type guard
if (!isPlanet(potentialPlanet)) throw new Error('is not a planet');

isAPromise

The type predicate of isAPromise allows you to narrow down the type of any variable that may be a promise

import { isAPromise } from 'type-fns';

// imagine we didn't know whether soonerOrLater is a promise or a string
const soonerOrLater: Promise<string> | string = Promise.resolve('hello') as any;

// typescript wont let you do things not common between the two types, rightly so
soonerOrLater.toLowerCase(); //  🛑 typescript error: `Property 'toLowerCase' does not exist on type 'string | Promise<string>'.`

// use the type-check to narrow down the the type to operate specifically per type
if (isAPromise(soonerOrLater)) {
  soonerOrLater.then((value) => value.toLowerCase()); // no error since type was narrowed to `Promise<string>`
} else {
  soonerOrLater.toLowerCase();  // no error since type was narrowed to `string`
}

isAFunction

The type predicate of isAFunction allows you to narrow down the type of any variable that may be a function

This is super helpful when writing apis that can take a literal or a function that creates the literal. For example

const superCoolApi = async ({
  getConfig
}: {
  getConfig: Config | () => Promise<Config>  // this can be the `Config` object or a function which resolves the `Config` object
}) => {
  const config: Config = isAFunction(getConfig)
    ? await getConfig() // if getConfig is a function, then execut it and await it to grab the config
    : getConfig; // otherwise, it is the config object already
}

changelog

Changelog

1.19.0 (2024-08-30)

Features

  • types: expose the Empty type (507fdb8)

1.18.0 (2024-08-18)

Features

  • array: expose ArrayWith type declaration (7855ac5)

1.17.0 (2024-07-27)

Features

  • practs: bump practs and resolve audit (e1e7844)

1.16.0 (2024-06-14)

Features

  • metadata: expose OmitMetadata generic (20bfea9)

1.15.0 (2024-05-25)

Features

  • types: add PickAny type, symmetric with PickOne (71cb283)

1.14.0 (2024-05-25)

Features

  • checks: add isKeyOf check (982f63d)

1.13.0 (2024-05-14)

Miscellaneous Chores

0.12.0 (2024-05-11)

Features

  • assure: expose generic withAssure wrapper; also, withAssure isPresent (009b29e)

Bug Fixes

  • lint: upgrade eslint to support typescript v5 (57530dc)

0.11.0 (2024-05-09)

Features

  • enum: add Literalize type to expand enum w literal union (e35381a)

0.10.0 (2024-04-28)

Features

  • enum: expand isOfEnum with backwards compat assess and assure (72ac7ac)

0.9.2 (2024-04-24)

Bug Fixes

  • omit: ensure omit satisfies Omit standard type (90552cc)
  • pick: ensure pick satisfies Pick standard type (cc4fd3d)

0.9.1 (2023-10-26)

Bug Fixes

  • checks: include deletedAt as a common metadata key (7791c38)
  • docs: remove outdated cicd badges (7c6499a)

0.9.0 (2023-07-16)

Features

  • companions: add pick and omit companion methods (2aed5a5), closes #16

Bug Fixes

  • audit: resolve security vulnerabilities with audit fix (90cdbd2)

0.8.1 (2023-02-16)

Bug Fixes

  • cicd: skip integration test provision step in cicd (e5e64ae)
  • practs: upgrade to declapract-typescript-ehmpathy best practices (6915660)

0.8.0 (2022-11-27)

Features

  • types: add DropFirst generic type (fc3a214)

0.7.0 (2022-11-26)

Features

  • checks: define the hasMetadata type check function (64b788f)

0.6.0 (2022-11-25)

Features

  • checks: add isNotUndefined and isNotNull checks (e810bdf)

0.5.1 (2022-11-25)

Bug Fixes

  • exports: actually export NotUndefined (1869b05)

0.5.0 (2022-11-25)

Features

  • types: add the NotUndefined generic type (bd613c2)

0.4.1 (2022-11-24)

Bug Fixes

  • exports: actually export isAPromise, isAFunction, PickOne (ad5b28f)

0.4.0 (2022-11-24)

Features

  • checks: add isAFunction, isAPromise, and PickOne type checks and generic type (981ae42)

Bug Fixes

  • cicd: update github actions, test scripts, and swap repo org to ehmpathy (b6a1458)
  • doc: fix comment describing has metadata in code (d7d2e55)
  • name: rename package to type-fns (66258d9)
  • tests: remove example of type error from tests (326123c)

0.3.0 (2022-01-03)

Features

  • checks: add the HasMetadata type modifier (85f0ca4)

0.2.1 (2021-11-16)

Bug Fixes

  • enum: forbid giving isOfEnum functions null or undefined as an input (98ec621)