ts-typedefs
This library is a handy collection of TypeScript plain and generic type definitions and interfaces for both frontend and backend. You may expect zero runtime overhead if you use imported items only in type contexts.
API documentation
Generated by typedoc
Contribution guidelines
Credits
This project was inspired by 'ts-essentials' library. Some type names were taken from them.
Quick API review
The most convenient way to explore 'ts-typedefs'
API is by easily browsing your editor's completion
list that shows signatures and descriptions for selected items. Types, functions, and classes names are intended to be super descriptive and intuitive.
All functional units provide typedoc
documentation in comments so it is easy for
IDEs to provide you with good hints.
Usage example
; ;
Provided type definitions and runtime units
Let's see them in details.
Objects
Obj<TValues, TKeys>
Defines an object with keys of type TKeys
, and all values of TValue
type.
; // { [key: string]: any; } ; // { [key: string]: boolean; } ; // { [key: number]: string; }; // { p1: number, p2: number; }
Class<TInstance, TArgs>
Defines constructor function type that instantiates TInstance
and accepts arguments of TArgs
type.
// new (...args: any) => User; // new (...args: [string, number]) => User;
InstanceType<TClass>
Defines an instance type of the given class or the type of its prototype
property.
TClass
may even be an abstract class, though those ones are not newable,
but the type of their instances can be obtained through their prototype
property.
; // plain class ; // User; // AbstractUser
ValueOf<TObj>
Defines a union type of all the values stored in TObj
.
/* number | string | null | boolean */; /* union type of all properties and methods of `Array<boolean>` */;
RemoveKeys<TSrcObj, TKeysUnion>
Defines the same object type as TSrcObj
, but without TKeysUnion
keys.
/* { id: number; login: string | null; isDisabled: boolean; }*/; /* { id: number; } */;
FilterProps<TObj, TApproveCond>
Defines the same type as TObj
but with particular properties filtered out according to TApproveCond
. TApproveCond
is a boolean operator tree structure that defines the criteria that the filtered values must match. All these operators are defined in Op
namespace.
/* { login: string; } */; /* { isDisabled: boolean; flag: boolean; }*/; /* { isDisabled: boolean; flag: boolean; id: number; }*/;
Because of some TypeScript limitations and bugs TApproveCond
tree must be not more than 5 levels deep (number of levels limitation may change, but it can only become greater).
MapValues<TSrcObj, TMappedValue>
Defines the same object type as TSrcObj
, but all values of TMappedValue
type.
DeepMapValues<>
variant maps values for all nested objects recursively.
/* { login: boolean; friend: boolean; } */;/*{ login: boolean; friend: { friendliness: boolean; ref: DeepMapValues<User, boolean> }}*/;
Merge<TObj1, TObj2>
Merge objects TObj1
and TObj2
.
Properties types from TObj2
override the ones defined on TObj1
.
This type is analogous to the return type of Object.assign()
/*{ p1: number; p2: number | null; p3: string; p4: O1;}*/; /*{ p1: number; p2: string; p3: boolean; p4: O1;}*/;
[Deep]Partial/Required<TObj>
Partial/Required<TObj, TKeys = keyof TObj>
defines the same type as TObj
but
with all TKeys
made optional/required.
DeepPartial/Required<>
defines the same type as TObj
but with all properties made recursively Partial/Required<>
.
This two types are actually exactly opposite to each other.
/*{ id?: undefined | number; name?: undefined | { first: string; }}*/; /*{ id?: number | undefined; name?: undefined | { first?: string | undefined; };}*/; ; // User; // User
[Deep]Readonly/Mutable<TObj>
Readonly/Mutable<TObj, TKeys = keyof TObj>
defines the same type as TObj
but
with all TKeys
made readonly/mutable.
DeepReadonly/Mutable<>
defines the same type as TObj
but with all properties made recursively Readonly/Mutable<>
.
This two types are actually exactly opposite to each other.
/*{ readonly id: number; readonly name: { first: string; }}*/; /*{ readonly id: number; readonly name: { readonly first: string; };}*/; ; // User; // User
DeepReadonly<>
is quite handy when you define deep readonly multidimensional arrays.
;// readonly (readonly (readonly number[])[])[]
OptionalLikelyUndefProps<TObj>
Defines the same type as TObj
, but adds 'optional' modifier ?
to all
properties that allow undefined
as their value type (this includes unknown
and any
).
/*{ bio?: string | undefined; secret?: unknown; name: string; // notice may-not-be `undefined` props don't get '?' modifier}*/;
Functions
[Async]Func<TArgs, TRetval, TThis>
Defines a Function subtype with the given arguments, return type and this
context. If it is AsyncFunc<>
TRetval
is packed into Promise<TRetval>
// (this: any, ...args: any) => unknown; // (this: any, ...args: [string, number | undefined]) => unknown; // (this: any, ...args: [boolean]) => void; // (this: User, ...args: [boolean]) => number; // (this: any, ...args: [string]) => Promise<User>
AsyncFuncReturnType<TAsyncFunc>
Defines the unpacked result type of the Promise
returned by the specified TAsyncFunc
.
// User; // User
Decorators
MethodDecorator<TArgs, TRetval, TMethNameLimit>
Defines a static or instance method decorator function type. TArgs
tuple type limits the arguments' type decorated method accepts, TRetval
limits the return type of the decorated method. TMethNameLimit
defines the limitation for method names this decorator may be applied to.
declare ;declare ;declare ; ;
PropertyDecorator<TPropType, TPropNameLimit>
Defines a static or instance property decorator function type.
declare ;;;
Logical
If<TCond, TIfTrue, TElse, TIfCondIsBool>
Sequentially performs the following logic:
Expands to TIfTrue
if TCond extends true
.
Expands to TElse
if TCond extends false
.
Expands to TIfCondIsBool
if TCond extends boolean
.
As a convention, enclose TCond
argument in parens.
; // number; // string; // bigint ; // string // You may use leading ampersand or pipe in order to explicitly separate branches visually; // number
Not<T, TIfTIsBool>
Defines false
unit type if T extends true
.
Defines true
unit type if T extends false
.
Defines TIfTIsBool
when T
is exactly boolean
type.
; // false; // true ; // number; // true
And/Nand<T>
Defines true
or false
accroding to the definition of and/nand(negated and)
logical operator.
It gets applied to all the argumets in the given tuple type T
.
; // true; // true; // false; // false ; // false
Or/Nor<T>
Defines true
or false
accroding to the definition of or/nor(negated or)
logical operator.
It gets applied to all the argumets in the given tuple type T
.
; // false; // false; // true; // true ; // false
[Not]Extends<TExtender, TExtendee>
Defines true
if TExtender
is assignable to TExtendee
, otherwise false
.
It verifies that you may physically assign a value of type TExtender
to TExtendee
.
That's why union types with excess members that are not assignable to TExtendee
will evaluate to false
.
; // false; // true; // true ; // false
AreSame<T1, T2>
Defines true
if T1
is exactly T2
, false
otherwise.
Even AreSame<unknown, any>
expands to false
. Only the same types expand to true
.
It doesn't tolerate co/bi/contravaraince, only the types of exactly the same shapes (excluding function types limitation) will cause to return true
.
Beware that this type works as vanilla extends
clause with function types,
so comparing functions is not that strict.
; // false; // true; // false ; // true; // true; // false
Is[Not]Any<TSuspect>
Defines true[false]
if TSuspect
is exactly of any
type, false[true]
otherwise.
; // true; // false; // false; // false ; // false; // true// ...
Is[Not]Unknown<TSuspect>
Defines true[false]
if TSuspect
is exactly of unknown
type, false[true]
otherwise.
; // true; // false ; // true// ...
Runtime
reinterpret<T>(value: any): T
C++ style operator, a syntactic sugar for writing casts like
value as any as T
when a simple value as T
cast cannot be performed.
Use it with caution!
This function is actually noop at runtime, all it does is it suppresses
'inability to cast' tsc error. It's better to use this function rather than
value as any as T
cast, because it amplifies your attention to such uneven
places in code and it may be easier to do a Ctrl + F search for these.
; Object.assignuserUpd, ; // For future devs: reinterpreting here, because userUpd has the same shape as `User`; // `typeof user` is `User`
class Debug.UnreachableCodeError
Class used to perform never
type value checks in unreachable code.
; if typeof val === 'string' else if typeof val === 'number' else switch suspect { case Enum.A: return; case Enum.B: return; default: }
Misc
Tag<TTarget, TTagName>
Defines nominal type by adding a property with TTagName
value to TTarget
.
TTagName
must be unique across your application, treat it like the name of
your nominal type.
With this type, you may pick particular subclass of values from the given type and force
your clients to filter other values that are assignable to TTarget
but don't
obey to your prerequisites, thus making them pay more attention to them.
;; // Prerequisites: `userId > 0` // Prerequisites: given string must be valid csv getUser-2; // compile errorgetUser58; // compile errorgetUser58 as PositiveInt; // fine (explicit cast pays your attention to prerequisites) parseCsv'\nbla bla'; // compile errorparseCsv'a,b,c\nd,e,f' as CsvString; // fine
UnionToIntersection<TUnion>
Defines an intersection type of all union's items.
Because of TypeScript boolean representation as type boolean = true | false
you get the following result:
UnionToIntersection<boolean>
is true & false
// string & number & number[];
UnpackPromise<TPromise>
Defines the type of value, which is passed to TPromise.then(cb)
cb
callback.
; // number;; // void; // Promise<string>;; // string;
PickAsOptional/Required/Readonly/Mutable/NullableProps<TObj, TKeys>
Shorthand for Partial/Required/Readonly/Mutable/NullableProps<Pick<TObj, TKeys>>
, but better optimized (into one mapped object type).
PickAsOptional<User, 'name' | 'id'> === Partial<Pick<User, 'name' | 'id'>>PickAsRequired<User, 'name' | 'id'> === Required<Pick<User, 'name' | 'id'>>PickAsReadonly<User, 'name' | 'id'> === Readonly<Pick<User, 'name' | 'id'>> // ...
[Deep]Nullable<T>
Nullable<T>
defines type T
that may also be null
or undefined
:
;
DeepNullable<T>
defines the same type as TObj
but with all properties made NonNullable<>
recursively.
/*Nullable<{ id?: Nullable<number>; name?: Nullable<{ first?: Nullable<string>; last?: Nullable<string>; }>;}>*/;
Primitive
Defines a union of all possible value types defined in the language,
null
and undefined
are considered to be primitive types.
;
TypeName
Defines a union of all possible strings retuned by applying typeof
operator.
;