npm
npm i ts-roids
pnpm
pnpm i ts-roids
If you're only using types, you can install it as a devDependency
.
And if you're using decorators, set this.
{
"compilerOptions": {
// ...
"experimentalDecorators": true
}
}
Requires TypesScript v5.0
+
Checkout the full API reference for all usage examples with details.
-
Prune<T,N = NotIncluded>
- Prune a typeT
by recursively omitting properties of typeN
(defaults toNotIncluded
). -
DeepToPrimitive<Obj>
- Recursively transforms an object type T into a type where all properties are replaced with their corresponding primitive types. -
Assign<Obj,ObjArr>
- Copies all enumerable own properties from one target object to a source array of objects. -
DeepImmutable<Obj>
- Recursively turns the proprties within a given object typeT
immutable, as in have all the properties with thereadonly
modifier. -
Deepmutable<Obj>
- Recursively mutates all the proprties within a given object typeT
, as in have all the properties without thereadonly
modifier. -
DeepRequired<Obj>
- Recursively make all object properties required. -
DeepNotRequired<Obj>
- Recursively make all object properties not required. -
DeepOmit<Obj,P>
- Recursively omits specified nested properties from an object, based on a given predicateP
. -
DeepPick<Obj,P>
- Deeply pick properties from a nested object, based on a given predicateP
. -
EmptyObject
- Represents any non-nullish value, basically{}
. -
EqualStrlen<S1, S2>
- Check if two stringsS1
andS2
have the same length. -
FilterBy<Obj, P>
- Filters keys from the object typeObj
based on a specified predicateP
. -
Flip<Obj>
- Flips keys with values of an object typeObj
. -
Float<N>
- Type representing a float. -
If<C, Do, Else>
- IfC
evaluatestrue
,Do
, otherwise returnElse
. -
IfEquals<T, P, Do, Else>
- Checks if typeT
is equal to typeP
. IfT
is equal toP
, the type resolves toDo
, otherwiseElse
. -
IfExtends<T, P, Do, Else>
- Checks if typeT
extends typeP
. if it does, the type resolves toDo
, otherwiseElse
. -
ImmutableKeys<Obj>
- Retrieves the keys that are immutable (readonly
) from an object of typeObj
. -
Integer<N>
- Represents an integer. -
And<B1,B2>
- Logical AND between two boolean types. -
ArrayFilter<Arr,P>
- Filters elements from an array based on a given predicate type. -
ArrayIncludes<Arr,T>
- Checks if a given type is in an array. -
ArrayIntersection<Arr>
- Calculates the intersection of the types within an arrayArr
of tuple types. -
ArrayMax<Arr>
- Extracts the maximumNumeric
(positive and negative) value in a given array. -
ArrayMin<Arr>
- Extracts the minimumNumeric
(positive and negative) value in a given array. -
ArrayTranspose<Arr>
- Transposes a given 2xN array or matrix, flipping the matrix over its diagonal, switching its row and column indices. -
ArrayUnique<Arr>
- Constructs a new array containing only unique elements from a given array type. -
EitherOneOrMany<T>
- Represents a type that can be either a single value of typeT
or an array of values of typeT
. -
Nullable
- Represents any non-nullish value, basically{}
. -
Equals<X,Y>
- Checks if two typesX
andY
are exactly equal. -
EvenNumeric<T>
- Represents an evenNumeric
. -
ExcludeNull<T>
- Excludesnull
from a typeT
. -
ExcludeNullable<T>
- ExcludesNullable
from a typeT
. -
ExcludeUndefined<T>
- Excludesundefined
from a typeT
. -
Extends<T,U>
- Evaluates whether one typeT
is assignable to another typeU
. -
FalsyProperties<T>
- Extracts falsy properties from an object typeT
. -
IsArrayIncludesTypeof<Arr, T>
- Checks if an array typeArr
includes one or more ofT
type. -
IsBigInt<T>
- Checks ifT
is abigint
. -
IsBoolean<T>
- Checks ifT
is aboolean
. -
IsDeepImmutable<Obj>
- Checks if all the nested properties of a given objectObj
are immutable. -
IsDeepMutable<Obj>
- Checks if all the nested properties of a given objectObj
are mutable. -
IsDeepNotRequired<Obj>
- Checks if all the properties of a given object (nested) are not required, as in, all properties have the?
modifier. -
IsDeepRequired<Obj>
- Checks if all the properties of a given object (nested) are required, as in, all properties do not have the?
modifier. -
IsExactlyAny<T>
- Checks if a typeT
is exactlyany
. -
IsExactlyBigInt<T>
- Checks if a typeT
is exactlybigint
not a subtype of it. -
IsExactlyNumber<T>
- Checks if a typeT
is exactlynumber
not a subtype of it. -
IsExactlyString<T>
- Checks if a typeT
is exactlystring
not a subtype of it. -
IsExactlySymbol<T>
- Checks if a typeT
is exactlysymbol
not a subtype of it. -
IsExactlyUnknown<T>
- Checks if a typeT
is exactlyunknown
not a subtype of it. -
IsFalsy<T>
- Checks if a given typeT
isFalsy
. -
IsFloat<N>
- Checks if a given typeT
is aFloat<N>
. -
IsFunction<T>
- Checks if a given typeT
is a function. -
IsInteger<N>
- Checks if a givenNumeric
is anInteger<N>
. -
IsNever<T>:
- Checks if a typeT
does not resolve, sonever
. -
IsNewable<T>
- Checks if a typeT
isNewable
. -
IsNullable<T>
- Checks if a typeT
isNullable
. -
IsNumber<T>
- Checks if a typeT
is anumber
. -
IsNumeric<T>
- Checks if a typeT
isNumeric
. -
IsObject<T>
- Checks if a given typeT
qualifies as an object. -
IsString<T>
- Check if a given typeT
is astring
. -
IsSymbol<T>
- Check if a given typeT
is asymbol
. -
IsTruthy<T>
- Check if a given typeT
resolves to a truthy value. -
Keys<T>
- Retrieves the union type of keys (property names) of a typeT
. -
MaybeUndefined<T>
- Type that mightundefined
. -
MutableKeys<Obj>
- Retrieves the keys that are mutable from an object of typeObj
. -
Nand<B1, B2>
- LogicalNAND
between two boolean typesB1
andB2
. -
NegativeFloat<N>
- Represents a negative (]-∞, 0[)Float<N>
. -
NegativeFloatString<S>
- Represents a negativeFloat<N>
parsed from astring
. -
NegativeInteger<N>
- Represents a negative (]-∞, 0[)Integer<N>
. -
NegativeIntegerString<S>
- Represents a negativeInteger<N>
parsed from astring
. -
NewType<New, Base>
- Represents a new unique type derived from an existing base type. (branded type) -
Newable
- Represents constructor functions that can be invoked using the new keyword. -
NonRequiredKeys<Obj>
- Returns all non required keys of an objectObj
, as in any property of an object that is marked with?
operator. -
Not<B>
- Negates a boolean typeB
. -
Nullable
- Represents a type that can either benull
orundefined
. -
Numeric
- Represents a type that can either benumber
orbigint
. -
NumerifyString<S>
- Turn a given string literal to aNumeric
, if possible. -
Methods<Obj>
- Get the literal names of keys that are methods in an object typeObj
. -
Properties<Obj>
- Get the literal names of keys that are properties in an object typeObj
. -
OddNumeric<T>
- Represents an oddNumeric
. -
OmitByType<Obj, T>
- Get a set of properties fromObj
whose type are not assignable toT
. -
OmitCommonKeys<Obj1, Obj2>
- Omit any common key between the the two objects,. -
OmitExactlyByType<Obj, T>
- Omit properties fromObj
whose type exactly matchesT
. -
Optional<T>
- Represents a type that may benull
, similar to Python'sOptional
type and Rust'sOption
enum. -
Or<B1, B2>
- LogicalOR
between two boolean typesB1
andB2
. -
PickByType<Obj, T>
- Pick fromObj
a set of properties that match the typeT
. -
PickCommonKeys<Obj1, Obj2>
- Get the common keys between two objects. -
PickExactlyByType<Obj, T>
- Get a set of properties fromObj
whose type exactly matchesT
. -
PositiveFloat<N>
- Represents a positive ([0, +∞[)Float<N>
. -
PositiveFloatString<S>
- Represents a positiveFloat<N>
parsed from astring
. -
PositiveInteger<N>
- Represents a positive ([0, +∞[)Integer<N>
. -
PositiveIntegerString<S>
- Represents a negativeInteger<N>
parsed from astring
. -
ReplaceKeys<Obj1,P,Obj2>
- Constructs a new type by replacing propertiesP
of typeObj
with object typeObj2
. -
RequiredKeys<Obj>
- Get the required keys of an object (shallow). -
SizedTuple<T,N>
- Creates a tuple with a specific length, where each element is of a given type. -
StringEndsWith<S,E>
- Checks if a stringS
ends withE
-
StringStartsWith<S,St>
- Checks if a stringS
starts withSt
-
StringifyPrimitive<P>
- Turns a givenPrimitive
value (exceptsymbol
) into its string representation. -
Strlen<S>
- Get the length of a stringS
. -
TestType<T1, T2, Expected>
- Tests if typeT1
andT2
are the same. -
TruthyProperties<T>
- Extracts truthy properties from an object typeT
. -
UnionToIntersection<U>
- As the name implies, it turns a union into an intersection. -
Vals<Obj>
- Get the set of type values in a given object. -
Xor<B1, B2>
- ExclusiveOR
between two boolean typesB1
andB2
.
@Final
- Marks an object final, as in one cannot inherit from it.@Sealed
- Seals an object.@Frozen
- Freezes an object.
Finalize and freeze objects
import type { Optional, NewType, MaybeUndefined } from 'ts-roids';
import { Final, Frozen } from 'ts-roids';
type Bar = NewType<'Bar', string>;
type Baz = NewType<'Baz', string>;
type Secret = NewType<'Secret', string>;
abstract class BaseFoo<T> {
abstract requestFoo(secret: Secret, baz: Baz): Optional<T>;
}
@Final
@Frozen
class Foo<T> extends BaseFoo<T> {
readonly foo: T;
bar: Optional<Bar>;
constructor(foo: T, bar?: MaybeUndefined<Bar>) {
super();
this.foo = foo;
this.bar = bar ?? null;
}
requestFoo(secret: Secret, baz: Baz): Optional<T> {
// A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value
if (
secret.concat().toLowerCase() === '123' &&
baz.concat().toLowerCase() === 'baz' &&
this.bar !== null
) {
return this.foo;
}
return null; // So you have to explicitly return null here.
}
}
class SubFoo extends Foo<string> {
constructor(foo: string) {
super(foo);
}
}
// No problem with instantiation
const foo = new Foo<string>('foo');
// Since the object is final:
// The line below will cause a TypeError: Cannot inherit from the final class Foo
const _ = new SubFoo('subFoo');
// Since the object is frozen:
// The line below will cause a TypeError: Cannot add property 'requestFoo', object is not extensible
foo.requestFoo = () => {
return 'not foo';
};
// The line below will cause a TypeError: Cannot assign to read only property 'bar'
foo.bar = 'not bar' as Bar;
The TypeScript team has not yet introduced a built-in final modifier yet, check
this, this and many other requests.
Although they introduced override
in v4.3
.
Decorators like @Final
provide a limited way to emulate final behavior, these are merely band-aids for now, until TS officially supports a true final modifier.
You can also seal an object btw.
@Sealed
class Person {
constructor(name: string, age?: number) {}
}
const john = new Person('John', 30);
// Existing properties can still be modified
john.age = 31; // No Errors
// Existing properties cannot be re-configured nor deleted
(john as any).email = '[email protected]'; // TypeError: Cannot add property email,
// object is not extensible
delete john.age; // TypeError: Cannot delete property 'age'
See releases.