More than 200 type utilities for TypeScript for applications, library, and type-level programming.
npm install type-plus
yarn add type-plus
pnpm add type-plus
With over 200 types in type-plus, it can become difficult to find the types you need.
Also, some types need to be updated as TypeScript continue to evolve.
Currently, we are updating type-plus with the following objective:
Top-level exports of type-plus will contain types and functions that do not expect the input to be a specific type. For example,
assertType()
, isType()
, and testType()
AnyType
or IsArray
It can also have types and functions for specific types if it is a common convention, or the is no ambiguity, or for backwards compatibility purpose.
Other type specific utilities will be added under their respective *Plus
namespaces such as ArrayPlus.At
or NumberPlus.Positive
.
Each type and utility function in type-plus will be updated to include examples and tags to indicate its category and behavior.
Each tag has an associated icon:
never
true
or false
Assertion Functions are special functions that asserts certain conditions of your program.
It is introduced in TypeScript 3.7.
They throw an error if the condition is not met, and return nothing otherwise.
These assertion functions are typically used in runtime, so that that type of the value can be narrowed down.
assertType
provides a generic assertion function,
as well as many assertion functions for builtin types.
๐ deprecated. Use assertType.as()
instead.
assertType<T>(subject, validator)
:
๐ฆassertion
: assert the subject
is type T
with the specified validator
.
If subject
fails the assertion,
a standard TypeError
will be thrown and provide better error info.
For example:
const s: unknown = 1
// TypeError: subject fails to satisfy s => typeof s === 'boolean'
assertType<boolean>(s, s => typeof s === 'boolean')
The message beautification is provided by tersify
.
๐ฆassertion
: assert the subject
is undefined
.
๐ฆassertion
: assert the subject
is not undefined
.
๐ฆassertion
: assert the subject
is null
.
๐ฆassertion
: assert the subject
is not null
.
๐ฆassertion
: assert the subject
is number
.
๐ฆassertion
: assert the subject
is not number
.
๐ฆassertion
: assert the subject
is boolean
.
๐ฆassertion
: assert the subject
is not boolean
.
๐ฆassertion
: assert the subject
is true
.
๐ฆassertion
: assert the subject
is not true
.
๐ฆassertion
: assert the subject
is false
.
๐ฆassertion
: assert the subject
is not false
.
๐ฆassertion
: assert the subject
is string
.
๐ฆassertion
: assert the subject
is not string
.
๐ฆassertion
: assert the subject
is function
.
๐ฆassertion
: assert the subject
is not function
.
๐ฆassertion
: assert the subject
is an Error
.
๐ฆassertion
: assert the subject
is not an Error
.
๐ deprecated. It does not work in all cases.
It passes for function that can be called with new
.
If the subject is an arrow function, it can still return true after compilation.
๐ฆassertion
: assert the subject
is never
.
๐ฆassertion
: creates a custom assertion function.
Using it to create a custom assertion function that provides better error messages.
The message beautification is provided by tersify
.
๐ฆassertion
: assert the subject
as T
without validator.
This works similar to manual assertion ;(subject as T)
User-defined type guard functions is a function which its return type is specified as x is T
.
๐ก๏ธ guard
: a generic type guard function
๐ deprecated
: use testType.true()
instead.
๐ deprecated
: use testType.false()
instead.
๐ deprecated
: use testType.never()
instead.
๐ deprecated
: use testType.equal()
instead.
Equal<A, B, Then = true, Else = false>
๐ deprecated. use IsEqual
instead. This will be converted to a โช๏ธ parse
.
IsEqual<A, B, Then = true, Else = false>
โญ predicate
: if A
and B
are the same.
NotEqual<A, B, Then = true, Else = false>
๐ deprecated. use IsNotEqual
instead. This will be converted to a โช๏ธ parse
.
IsNotEqual<A, B, Then = true, Else = false>
:
โญ predicate
: check if A
and B
are not the same.
Extendable<A, B, Then = A, Else = never>
โช๏ธ parse
: check if A
extends B
.
IsExtend<A, B, Then = true, Else = false>
โญ predicate
: check if A
extends B
.
NotExtendable<A, B, Then = A, Else = never>
:
โช๏ธ parse
: check if A
not extends B
.
IsNotExtend<A, B, Then = true, Else = false>
:
โญ predicate
: check if A
not extends B
.
IsAssign<A, B, Then = true, Else = false>
๐ deprecated
: use CanAssign
instead.
CanAssign<A, B, Then = true, Else = false>
:
โญ predicate
: check can A
assign to B
.
A typical usage is using it with assertType
:
assertType.isFalse(false as CanAssign<boolean, { a: string }>)
assertType.isTrue(true as CanAssign<{ a:string, b:number }, { a: string }>)
StrictCanAssign<A, B, Then = true, Else = false>
โญ predicate
: can A
strictly assign to B
When A
is a union, all branches must be assignable to B
.
StrictCanAssign<number | string, number> // false
StrictCanAssign<number | string, number | string> // true
canAssign<T>(): (subject) => true
โญ๐ป predicate
, compile-time
Returns a compile-time validating function to ensure subject
is assignable to T
.
const isConfig = canAssign<{ a: string }>()
assertType.isTrue(isConfig({ a: 'a' }))
canAssign<T>(false): (subject) => false
:
โญ๐ป predicate
, compile-time
Returns a compile-time validating function to ensure subject
is not assignable to T
.
const notA = canAssign<{ a: string }>(false)
assertType.isTrue(notA({ a: 1 }))
notA({ a: '' }) // TypeScript complains
type-plus privides type checking utilities for every type.
Each type has at least 4 type checks.
Using string
as an example, there are StringType<T>
, IsString<T>
, NotStringType<T>
, and IsNotString<T>
.
Some types will have more checks, such as boolean
has StrictBooleanType<T>
, TrueType<T>
, FalseType<T>
.
You can learn more in their respective sections:
ArrayType
: Filter T
to ensure it is an array, excluding tuple.IsArray
: Validate that T
is an array, excluding tuple.NotArrayType
: Filter T
to ensure it is not an array, excluding tuple.IsNotArrayType
: Validate that T
is not an array, excluding tuple.At
: Gets the type of the array or tuple at positive or negative index N
.Concat
: Concats two arrays or tuples.FindFirst
: Find the first type in the array or tuple A
that matches Criteria
.FindLast
Some
Filter
: Filter the array or tuple A
, keeping entries satisfying Criteria
.KeepMatch
: Keeps entries satisfying Criteria
in array or tuple A
.Head
: Gets the first entry in the tuple or the type of array T
.IntersectOfProps
MapToProp
Last
: Gets the last entry in the tuple or the type of array T
.literalArray
PadStart
reduceWhile
Reverse
PropUnion
UnionOfProps
UnionOfValues
ArrayPlus.At
ArrayPlus.Concat
ArrayPlus.Entries
ArrayPlus.Find
: Finds the type in array A
that matches Criteria
.ArrayPlus.FindLast
ArrayPlus.Reverse
ArrayPlus.SplitAt
ArrayPlus.Some
โช๏ธ parse
: if T
is bigint
or bigint literal.
โญ predicate
: if T
is bigint
or bigint literal.
โช๏ธ parse
: if T
is not bigint
or bigint literal.
โญ predicate
: if T
is not bigint
or bigint literal.
โช๏ธ parse
: if T
is exactly bigint
.
โญ predicate
: if T
is exactly bigint
.
โช๏ธ parse
: if T
is not exactly bigint
.
โญ predicate
: if T
is not exactly bigint
.
โช๏ธ parse
: T === boolean
.
โญ predicate
: T === boolean
โช๏ธ parse
: T !== boolean
.
โญ predicate
: T !== boolean
โช๏ธ parse
: T === function
.
โญ predicate
: T === function
โช๏ธ parse
: T !== function
.
โญ predicate
: T !== function
AnyFunction<P, R>
๐จ utilities
: a generic type for any function
ExtractFunction<F>
๐จ utilities
: extract the function signature from a type F
.
extractFunction(fn: F)
๐จ utilities
: adjust type of fn
to its function signature only.
inspect<T>(value: T, inspector?: (v: T) => void)
๐จ utilities
: inspect a value and return it. Inspector defaults to console.dir()
โช๏ธ parse
: T === never
.
โญ predicate
: T === never
โช๏ธ parse
: T !== never
.
โญ predicate
: T !== never
โช๏ธ parse
: T === null
.
โญ predicate
: T === null
โช๏ธ parse
: T !== null
.
โญ predicate
: T !== null
โช๏ธ parse
: is the type T
number
.
โญ predicate
: is the type T
number
.
โช๏ธ parse
: is the type T
not number
.
โญ predicate
: is the type T
not number
.
โช๏ธ parse
: is the type T
exactly number
.
โญ predicate
: is the type T
exactly number
.
โช๏ธ parse
: is the type T
not exactly number
.
โญ predicate
: is the type T
not exactly number
.
๐ definition
: number | bigint
.
๐ definition
: 0 | 0n
โช๏ธ parse
: is integer.
โญ predicate
: is integer.
โช๏ธ parse
: is not integer.
โญ predicate
: is not integer.
๐โญ deprecated
, predicate
: is integer. Use IsInteger
instead.
โช๏ธ parse
: is negative.
โญ predicate
: is negative.
โช๏ธ parse
: is not negative.
โญ predicate
: is not negative.
โช๏ธ parse
: is positive.
โญ predicate
: is positive.
โช๏ธ parse
: is not positive.
โญ predicate
: is not positive.
filterKey()
๐จ utilities
: type adjusted filter by key.
findKey()
๐จ utilities
: type adjusted find by key.
forEachKey()
๐จ utilities
: type adjusted for each by key.
HasKey<T, K>
๐จ utilities
: predicate type checking T
has key K
.
hasKey()
๐จ utilities
: function of HasKey
.
IsRecord<T>
๐จ utilities
: logical
predicate for Record
.
KeysWithDiffTypes<A, B>
๐จ utilities
: gets the keys common in A
and B
but with different value type.
mapKey()
๐จ utilities
: type adjusted map by key.
RecordValue<R>
๐จ utilities
: gets the value type T
from Record<any, T>
reduceByKey()
๐จ utilities
: type adjusted reduce by key.
someKey()
๐จ utilities
: type adjusted some by key.
SpreadRecord<A, B>
๐จ utilities
: type for {...a, ...b}
when both a
and b
are Record
for array, just do [...A, ...B]
.
AwaitedProp<T, V>
๐จ utilities
: Awaited
on specified props P
in T
.
isPromise<R>(subject: any)
๐จ utilities
: isPromise()
type guard.
MaybePromise<T>
๐จ utilities
: Alias of T | Promise<T>
.
PromiseValue<P>
๐จ utilities
: Gets the type within the Promise.
PromiseValueMerge<P1, P2, ...P9>
๐จ utilities
: Merge the values of multiple promises.
mapSeries()
๐จ utilities
: Similar to bluebird.mapSeries()
but works with async
/await
.
transformMaybePromise(value, transformer)
๐จ utilities
: Apply the transformer
to the value
.
It is also exported under MaybePromise.transform()
.
โช๏ธ parse
: is string
.
โญ predicate
: is string
.
โช๏ธ parse
: is not string
.
โญ predicate
: is not string
.
โช๏ธ parse
: is symbol
.
โญ predicate
: is symbol
.
โช๏ธ parse
: is not symbol
.
โญ predicate
: is not symbol
.
TupleType
: Filter T
to ensure it is a tuple, excluding array.IsTuple
: Validate that T
is a tuple, excluding array.NotTupleType
: Filter T
to ensure it is not an tuple, excluding array.IsNotTuple
: Validate that T
is not an tuple, excluding array.CommonPropKeys
: Gets the common property keys of the elements in tuple T
.CommonKeys
: Deprecated. Please use CommonPropKeys
instead.DropFirst
: Drops the first entry in the tupleT
.DropLast
: Drops the last entry in the tupleT
.
CreateTuple<L, T>
๐จ utilities
: creates tuple<T>
with L
number of elements.
drop(array, value)
๐จ utilities
: drop a particular value from an array.
DropMatch<A, Criteria>
๐จ utilities
: drops entries matching Criteria
in array or tuple A
.
DropUndefined<A>
๐จ utilities
: drop undefined entries from array of tuple A
.
โช๏ธ parse
: T === undefined
.
โญ predicate
: T === undefined
โช๏ธ parse
: T !== undefined
.
โญ predicate
: T !== undefined
โช๏ธ parse
: T === unknown
.
โญ predicate
: T === unknown
โช๏ธ parse
: T !== unknown
.
โญ predicate
: T !== unknown
โช๏ธ parse
: T === void
.
โญ predicate
: T === void
โช๏ธ parse
: T !== void
.
โญ predicate
: T !== void
type-plus privides some testing utilities to help you test your types.
One of the key utilities is testType
.
import { testType } from 'type-plus'
testType.any<T>(true) // T is `any`
testType.equal<A, B>(true) // A is equal to B
testType.never<T>(false) // T is not `never`
You can learn more about them in the docs.
KeyTypes
๐ definition
: type of all keys.
PrimitiveTypes
๐ definition
: all primitive types, including Function
, symbol
, and bigint
.
ComposableTypes
๐ definition
: Types that can contain custom properties. i.e. object
, array
, function
.
NonComposableTypes
๐ definition
: Types that cannot contain custom properties. i.e. not composable.
JSONPrimitive
๐ definition
: primitive types valid in JSON
JSONObject
๐ definition
: JSON object
JSONArray
๐ definition
: JSON array
JSONTypes
๐ definition
: all JSON compatible types.
JSONTypes.get<T>(obj, ...props)
๐จ utilities
: get a cast value in JSON
import { JSONTypes } from 'type-plus'
const someJson: JSONTypes = { a: { b: ['z', { c: 'miku' }]}}
JSONTypes.get<string>(someJson, 'a', 'b', 1, 'c') // miku
ANotB<A, B>
๐จ utilities
: get object with properties in A
and not in B
, including properties with a different value type.
BNotA<A, B>
๐จ utilities
: flip of ANotB
as<T>(subject)
๐จ utilities
: assert subject
as T
. Avoid ASI issues such as ;(x as T).abc
asAny(subject)
๐จ utilities
: assert subject
as any
. Avoid ASI issue such as ;(x as any).abc
EitherAnd<A, B, [C, D]>
๐๐จ deprecated
,utilities
: Renamed to EitherOrBoth
. combines 2 to 4 types as A | B | (A & B)
.
This is useful for combining options.
EitherOrBoth<A, B, [C, D]>
๐จ utilities
: combines 2 to 4 types as A | B | (A & B)
.
This is useful for combining options video.
Except<T, K>
๐๐จ deprecated
,utilities
: same as Omit<T, K>
.
ExcludePropType<T, U>
๐จ utilities
: excludes type U
from properties in T
.
KeyofOptional<T>
๐จ utilities
: keyof
that works with Record<any, any> | undefined
.
KnownKeys<T>
๐จ utilities
: extract known (defined) keys from type T
.
LeftJoin<A, B>
๐จ utilities
: left join A
with B
NonNull<T>
๐จ utilities
: remove null
NonNullable<T>
(built-in)
๐จ utilities
: adjust the type not to nullable
NonUndefined<T>
๐จ utilities
: remove undefined
Omit<T, K>
๐จ utilities
: From T
, pick a set of properties whose keys are not in the union K
. This is the opposite of Pick<T, K>
.
OptionalKeys<T>
๐จ utilities
: gets keys of optional properties in T
.
PartialExcept<T, U>
๐๐จ deprecated
,utilities
: same as PartialOmit<T, U>
.
PartialOmit<T, U>
๐จ utilities
: makes the properties not specified in U
becomes optional.
PartialPick<T, U>
๐จ utilities
: makes the properties specified in U
becomes optional.
Pick<T, K>
๐จ utilities
: pick properties K
from T
. Works with unions.
RecursivePartial<T>
๐จ utilities
: make type T
optional recursively.
RecursiveRequired<T>
๐จ utilities
: make type T
required recursively.
ReplaceProperty<T, K, V>
๐จ utilities
: replace property K
in T
with V
.
RequiredKeys<T>
๐จ utilities
: gets keys of required properties in T
.
RequiredPick<T, U>
๐จ utilities
: makes the properties specified in U
become required.
RequiredExcept<T, U>
๐จ utilities
: makes the properties not specified in U
become required.
RecursiveIntersect<T, U>
๐จ utilities
: intersect type U
onto T
recursively.
ValueOf<T>
๐จ utilities
: type of the value of the properties of T
.
Widen<T>
๐จ utilities
: widen literal types.
PropType
๐ ...no helper type for this. Just do YourType['propName']
.
Type predicates are type alias that returns true
or false
.
They can be used to compose complex types.
HasKey<T, K>
๐จ utilities
: predicate type checking T
has key K
.
IsAny<T>
๐จ utilities
: T === any
(updated to impl: expect-type).
IsBoolean<T>
๐จ utilities
: check for boolean
, but not for true
nor false
.
IsDisjoint<A, B>
๐จ utilities
: is A
and B
is a disjoint set.
IsEmptyObject<T>
๐จ utilities
: is T === {}
.
IsLiteral<T>
๐จ utilities
: is T
a literal type (literal string or number).
If<Condition, Then = true, Else = false>
๐จ utilities
: if statement
And<A, B, Then = true, Else = false>
๐จ utilities
: logical AND
Or<A, B, Then = true, Else = false>
๐จ utilities
: logical OR
Xor<A, B, Then = true, Else = false>
๐จ utilities
: logical XOR
Not<X, Then = true, Else = false>
๐จ utilities
: logical NOT
Note that these types work correctly with the boolean
type.
e.g.:
type R = And<boolean, true> // boolean
type R = Not<boolean> // boolean`
There is a problem with generic distribution: https://github.com/microsoft/TypeScript/issues/41053 So you may encounter some weird behavior if your logic is complex.
The math types in type-plus
works with most numeric types.
It works with number
and bigint
, positive and negative number, including floating point numbers.
It will cast the type between number
and bigint
if needed.
Abs<N, Fail = never>
๐จ utilities
: Abs(N)
.
Max<A, B, Fail = never>
๐จ utilities
: max(A, B)
GreaterThan<A, B>
๐จ utilities
: A > B
.
Add<A, B>
๐จ utilities
: A + B
.
Subtract<A, B>
๐จ utilities
: A > B
.
Increment<A>
๐จ utilities
: alias of Add<A, 1>
.
Decrement<A>
๐จ utilities
: alias of Subtract<A, 1>
.
Multiply<A, B
๐จ utilities
: A * B
.
amend(subject)...
๐จ utilities
: amend subject as union or intersect of T
.
facade(subject, ...props)
๐จ utilities
: create a facade of subject
.
getField(subject, key, defaultValue)
๐จ utilities
: get a field from a subject. Works against nullable and optional subject.
hasKey()
๐จ utilities
: function of HasKey
.
hasProperty(value, prop)
๐จ utilities
: assert value
has property prop
. This will pick the correct union type.
isConstructor(subject)
๐จ utilities
: type guard subject
is a constructor.
isSystemError(code, err)
๐จ utilities
: type guard err
with NodeJS error code.
omit(obj, ...props)
๐จ utilities
: omit properties from obj
.
pick(obj, ...props)
๐จ utilities
: pick properties from obj
.
record<K, V>(value?)
๐จ utilities
: create a Record<K, V>
without extra object prototype.
record<R>(value?)
๐จ utilities
: create a record R
(e.g. { a: number }
) without extra object prototype.
required(...)
๐จ utilities
: merge options and remove Partial<T>
. From unpartial
requiredDeep(...)
๐จ utilities
: merge options deeply and remove Partial<T>
. From unpartial
split(target, ...splitters)
๐จ utilities
: split one object into multiple objects.
stub<T>(value)
๐จ utilities
: stub a particular type T
.
stub.build<T>(init?)
๐จ utilities
: build a stub for particular type T
.
typeOverrideIncompatible<T>()
๐จ utilities
: override only the incompatible portion between two types.
type A = {
foo: boolean,
bar: string,
baz: string
}
const overrider = typeOverrideIncompatible<A>()
const source = {
foo: 1,
bar: 'bar',
baz: 'baz'
}
// only the `foo` property is available to override.
overrider(source, { foo: !!source.foo })
unpartial()
๐จ utilities
: merge options and remove Partial<T>
values. From unpartial
context()
๐จ utilities
: a context builder.
This is useful to build context for functional programming.
It is a sync version of the AsyncContext
from async-fp.
import { context } from 'type-plus'
// { a: 1, b: 2 }
const ctx = context({ a: 1 })
.extend(c => ({ b: c.a + 1 }))
.build()
The TypeScript type system is structural.
In some cases, we want to express a type with nominal behavior.
type-plus
provides two kinds of nominal types: Brand
and Flavor
.
Brand<B, T>
:
brand(type, subject?)
:
Branded nominal type is the stronger nominal type of the two. It disallows unbranded type assigned to it:
const a = brand('a', { a: 1 })
const b = { a: 1 }
a = b // error
subject
can be any type, from primitive to strings to objects.
brand(type)
:
If you do not provide subject
, brand(type)
will return a brand creator,
so that you can use it to create multiple branded values:
const nike = brand('nike')
const shirt = nike('shirt')
const socks = nike('socks')
Flavor<F, T>
:
flavor(type, subject?)
:
The key difference between Flavor
and Brand
is that
unflavored type can be assigned to Flavor
:
let f = flavor('orange', 'soda')
f = 'mist' // ok
Also, Brand
of the same name can be assigned to Flavor
,
but Flavor
of the same name cannot be assigned to Brand
.
nominalMatch(a, b)
:
๐จ utilities
: compare if the two values are nominally equal.
Works with both Brand
and Flavor
.
const b1 = brand('x', 1)
const b2 = brand('y', 1)
nominalMatch(b1, b2) // false
ChainFn<T>: T
๐จ utilities
: chain function that returns the input type.
compose(...fns): F
๐จ utilities
: compose functions
Some code in this library is created by other people in the TypeScript community. I'm merely adding them in and maybe making some adjustments. Whenever possible, I add attribution to the person who created those codes in the file.
Pipe
.