ts-roids v1.40.0
ts-roids
100+ types and decorators to bullet proof TypeScript even more.
Types
PartializedUnion<T>- Creates a union type where each variant has its specific properties required, while other properties are optional.Prune<T,N = NotIncluded>- Prune a typeTby 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 typeTimmutable, as in have all the properties with thereadonlymodifier.Deepmutable<Obj>- Recursively mutates all the proprties within a given object typeT, as in have all the properties without thereadonlymodifier.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 stringsS1andS2have the same length.PartialExcept<T, P>- Makes all properties inToptional except those inKwhich remain required.FilterBy<Obj, P>- Filters keys from the object typeObjbased on a specified predicateP.Flip<Obj>- Flips keys with values of an object typeObj.Float<N>- Type representing a float.If<C, Do, Else>- IfCevaluatestrue,Do, otherwise returnElse.IfEquals<T, P, Do, Else>- Checks if typeTis equal to typeP. IfTis equal toP, the type resolves toDo, otherwiseElse.IfExtends<T, P, Do, Else>- Checks if typeTextends 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.Abs<N>- Get the absolute value of aNumeric.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 arrayArrof 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 typeTor an array of values of typeT.Nullable- Represents any non-nullish value, basically{}.Equals<X,Y>- Checks if two typesXandYare exactly equal.EvenNumeric<T>- Represents an evenNumeric.ExcludeNull<T>- Excludesnullfrom a typeT.ExcludeNullable<T>- ExcludesNullablefrom a typeT.ExcludeUndefined<T>- Excludesundefinedfrom a typeT.KeysOfUnion<T>- Extracts the union of keys from a given union of object types, useful for accessing all possible keys in unions.Simplify<T>- Flattens the structure of a type by resolving intersections and simplifying nested mapped types, enhancing readability.Extends<T,U>- Evaluates whether one typeTis assignable to another typeU.Falsy- Represents a type that is falsy JavaScript.FalsyProperties<T>- Extracts falsy properties from an object typeT.IsArrayIncludesTypeof<Arr, T>- Checks if an array typeArrincludes one or more ofTtype.IsBigInt<T>- Checks ifTis abigint.IsBoolean<T>- Checks ifTis aboolean.IsDeepImmutable<Obj>- Checks if all the nested properties of a given objectObjare immutable.IsDeepMutable<Obj>- Checks if all the nested properties of a given objectObjare 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 typeTis exactlyany.IsExactlyBigInt<T>- Checks if a typeTis exactlybigintnot a subtype of it.IsExactlyNumber<T>- Checks if a typeTis exactlynumbernot a subtype of it.IsExactlyString<T>- Checks if a typeTis exactlystringnot a subtype of it.IsExactlySymbol<T>- Checks if a typeTis exactlysymbolnot a subtype of it.IsExactlyUnknown<T>- Checks if a typeTis exactlyunknownnot a subtype of it.IsFalsy<T>- Checks if a given typeTisFalsy.IsFloat<N>- Checks if a given typeTis aFloat<N>.IsFunction<T>- Checks if a given typeTis a function.IsInteger<N>- Checks if a givenNumericis anInteger<N>.IsNever<T>:- Checks if a typeTdoes not resolve, sonever.IsNewable<T>- Checks if a typeTisNewable.IsNullable<T>- Checks if a typeTisNullable.IsNumber<T>- Checks if a typeTis anumber.IsNumeric<T>- Checks if a typeTisNumeric.IsObject<T>- Checks if a given typeTqualifies as an object.IsString<T>- Check if a given typeTis astring.IsSymbol<T>- Check if a given typeTis asymbol.IsTruthy<T>- Check if a given typeTresolves to a truthy value.Keys<T>- Retrieves the union type of keys (property names) of a typeT.Maybe<T>- Type that might beNullableMaybeUndefined<T>- Type that mightundefined.MutableKeys<Obj>- Retrieves the keys that are mutable from an object of typeObj.Nand<B1, B2>- LogicalNANDbetween two boolean typesB1andB2.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 benullorundefined.Numeric- Represents a type that can either benumberorbigint.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 fromObjwhose type are not assignable toT.OmitCommonKeys<Obj1, Obj2>- Omit any common key between the the two objects,.OmitExactlyByType<Obj, T>- Omit properties fromObjwhose type exactly matchesT.Optional<T>- Represents a type that may benull, similar to Python'sOptionaltype and Rust'sOptionenum.Or<B1, B2>- LogicalORbetween two boolean typesB1andB2.PickByType<Obj, T>- Pick fromObja 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 fromObjwhose 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.Primitive- All primitive types.ReplaceKeys<Obj1,P,Obj2>- Constructs a new type by replacing propertiesPof typeObjwith 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 stringSends withEStringStartsWith<S,St>- Checks if a stringSstarts withStStringifyPrimitive<P>- Turns a givenPrimitivevalue (exceptsymbol) into its string representation.Strlen<S>- Get the length of a stringS.TestType<T1, T2, Expected>- Tests if typeT1andT2are 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>- ExclusiveORbetween two boolean typesB1andB2.
Decorators
@Final- Marks an object final, as in one cannot inherit from it.@Sealed- Seals an object.@Frozen- Freezes an object.
Basic Usage
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 = 'john@doe.com'; // TypeError: Cannot add property email,
// object is not extensible
delete john.age; // TypeError: Cannot delete property 'age' Changelog
See releases.
License
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago