Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
type-plus
Advanced tools
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 of the 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
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
.FAQs
Provides additional types for TypeScript.
We found that type-plus demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.