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,
}
}>
}) => {
}
await findWrench({
size: {
metric: { millimeters: 16 }
}
})
await findWrench({
size: {
imperial: { inches: '5/16' }
}
})
await findWrench({
size: {
metric: { millimeters: 16 } ,
imperial: { inches: '5/16' }
}
})
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';
const stringsOrNulls = ['success:1', 'success:2', null, 'success:3', null];
const strings = stringsOrNulls.filter(isPresent);
strings.map((string) => string.toUpperCase());
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';
enum Planet {
...
VENUS = 'VENUS',
EARTH = 'EARTH',
MARS = 'MARS',
...
}
const isPlanet = createIsOfEnum(Planet);
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';
const soonerOrLater: Promise<string> | string = Promise.resolve('hello') as any;
soonerOrLater.toLowerCase();
if (isAPromise(soonerOrLater)) {
soonerOrLater.then((value) => value.toLowerCase());
} else {
soonerOrLater.toLowerCase();
}
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()
: getConfig;
}