• Stars
    star
    591
  • Rank 75,679 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

TypeScript common pattern shortcut definitions / utility gist library

tsdef

TypeScript common patterns shortcuts definitions snippets utility gist library

npm version npm npm type definitions Build Status Dependency Status GitHub

Get Started

npm install -D tsdef

or

yarn add -D tsdef

How to Use

import { Nullable, NonNull } from 'tsdef';

const nullableString: Nullable<string> = null; // ok

const nonNullString: NonNull<string | null> = null; // error

Documentation (Source Code)

export type nil = null | undefined;

export type Nilable<T> = T | nil;
export type Nullable<T> = T | null;
export type Undefinable<T> = T | undefined;

export type MaybeNil<T> = T | nil;
export type MaybeNull<T> = T | null;
export type MaybeUndefined<T> = T | undefined;
export type MaybePromise<T> = T | Promise<T>;
export type MaybeArray<T> = T | T[];
export type MaybeAsReturnType<T> = T | ((...args: any) => T);

// removes both null or undefined from T
export type NonNil<T> = T extends nil ? never : T;

// removes null from T
export type NonNull<T> = T extends null ? never : T;

// removes undefined from T
export type NonUndefined<T> = T extends undefined ? never : T;

// make all properties nilable
export type NilableProps<T> = { [P in keyof T]?: T[P] | nil };

// make all properties nullable
export type NullableProps<T> = { [P in keyof T]: T[P] | null };

// make all properties undefinable
export type UndefinableProps<T> = { [P in keyof T]?: T[P] | undefined };

// make all properties non nilable
export type NonNilProps<T> = { [P in keyof T]-?: NonNil<T[P]> };

// make all properties non null
export type NonNullProps<T> = { [P in keyof T]: NonNull<T[P]> };

// make all properties non undefined
export type NonUndefinedProps<T> = { [P in keyof T]-?: NonUndefined<T[P]> };

// make all properties required
export type RequiredProps<T> = { [P in keyof T]-?: T[P] };

// make all properties non readonly
export type WritableProps<T> = { -readonly [P in keyof T]: T[P] };

// string | number | symbol
export type AnyKey = keyof any;

// matches any functions
export type AnyFunction = (...args: any) => any;

// matches any constructors
export type AnyConstructor = new (...args: any) => any;

// matches classes
export interface AnyClass {
  prototype: any;
  new (...args: any): any;
}

// matches prototypes
export interface AnyPrototype {
  constructor: any;
}

// matches any objects
export interface AnyObject {
  [key: string]: any;
  [key: number]: any;
}

// matches objects with string keys
export interface AnyObjectWithStringKeys {
  [key: string]: any;
}

// matches objects with number keys
export interface AnyObjectWithNumberKeys {
  [key: number]: any;
}

// without some keys
export type ExcludeKeys<T, K extends AnyKey> = Omit<T, K>;

// values of object
export type ValueOf<T> = T[keyof T];

// get a property
export type Property<T, K> = K extends keyof T ? T[K] : never;

// get keys with values of given type
export type KeyOfType<T, U> = {
  [P in keyof T]-?: T[P] extends U ? P : never
}[keyof T];

// get keys with values of given sub type
// For some reason, this works and KeyOfType doesn't when U = undefined
export type KeyOfSubType<T, U> = {
  [P in keyof T]-?: U extends T[P] ? P : never
}[keyof T];

// make some keys optional
export type WithOptionalKeys<T, K extends keyof T> = Omit<T, K> &
  Partial<Pick<T, K>>;

// make some keys nilable
export type WithNilableKeys<T, K extends keyof T> = Omit<T, K> &
  NilableProps<Pick<T, K>>;

// make some keys nullable
export type WithNullableKeys<T, K extends keyof T> = Omit<T, K> &
  NullableProps<Pick<T, K>>;

// make some keys undefinable
export type WithUndefinableKeys<T, K extends keyof T> = Omit<T, K> &
  UndefinableProps<Pick<T, K>>;

// make some keys non nil
export type WithNonNilKeys<T, K extends keyof T> = Omit<T, K> &
  NonNilProps<Pick<T, K>>;

// make some keys non null
export type WithNonNullKeys<T, K extends keyof T> = Omit<T, K> &
  NonNullProps<Pick<T, K>>;

// make some keys non undefined
export type WithNonUndefinedKeys<T, K extends keyof T> = Omit<T, K> &
  NonUndefinedProps<Pick<T, K>>;

// make all properties optional recursively including nested objects.
// keep in mind that this should be used on json / plain objects only.
// otherwise, it will make class methods optional as well.
export type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends Array<infer I>
    ? Array<DeepPartial<I>>
    : DeepPartial<T[P]>
};

// first object properties excluding common keys with second object
export type DiffObjects<T, U> = Omit<T, keyof U>;

// union of two objects
export type UnionObjects<
  T extends AnyObject,
  U extends AnyObject
> = DiffObjects<T, U> &
  { [P in keyof T & keyof U]: T[P] | U[P] } &
  DiffObjects<U, T>;

// similar to Object.assign
export type OverwriteProps<T, U> = U & DiffObjects<T, U>;

// get arguments type
export type Arguments<T extends AnyFunction> = Parameters<T>;

// get arguments type
export type FirstArgument<T extends AnyFunction> = T extends (
  arg: infer A,
  ...args: any
) => any
  ? A
  : never;

// get return value type
export type Return<T extends AnyFunction> = ReturnType<T>;

// get return type if a function, otherwise return itself
export type MaybeReturnType<T> = T extends (...args: any[]) => infer R ? R : T;

// get instance type of class
export type InstanceOf<T extends AnyConstructor> = InstanceType<T>;

// get promise return type
// PromisedType<Promise<T>> = T
export type PromisedType<T extends Promise<any>> = T extends Promise<infer R>
  ? R
  : never;

// get promise return type if promise, otherwise return itself
// MaybePromisedType<T | Promise<T>> = T
export type MaybePromisedType<T> = T extends Promise<infer R> ? R : T;

// get promise return type
export type MaybeAsyncReturnType<T extends AnyFunction> = MaybePromisedType<
  ReturnType<T>
>;

// get array item type
export type ItemType<T extends any[]> = T extends Array<infer I> ? I : never;

// get thunk for type
export type Thunk<T> = () => T;

// get thunk or self
export type MaybeThunk<T> = T | Thunk<T>;

// get return type of thunk
export type Unthunk<T extends Thunk<any>> = T extends Thunk<infer R>
  ? R
  : never;

// get return type if thunk, otherwise get self
export type MaybeUnthunk<T> = T extends Thunk<infer R> ? R : T;

// get inferred type of array item or return value or promised value
export type Unpack<T> = T extends Array<infer I>
  ? I
  : T extends (...args: any) => infer R
  ? R
  : T extends Promise<infer P>
  ? P
  : T;

// InheritClass<C1, C2>: class C1 extends C2 {}
export type InheritClass<C1 extends AnyClass, C2 extends AnyClass> = {
  prototype: OverwriteProps<C2['prototype'], C1['prototype']>;
  new (...args: ConstructorParameters<AnyClass>): OverwriteProps<
    C2['prototype'],
    C1['prototype']
  >;
} & OverwriteProps<C2, C1>;

// return Then if T is not null nor undefined, otherwise return False
// test null and undefined separately to prevent side effect from args distribution
export type IsNonNil<T, True, False = never> = null extends T
  ? False
  : undefined extends T
  ? False
  : True;

// return True if T is not null, otherwise return False
export type IsNonNull<T, True, False = never> = null extends T ? False : True;

// return True if T is not undefined, otherwise return False
export type IsNonUndefined<T, True, False = never> = undefined extends T
  ? False
  : True;

// return True if T is `never`, otherwise return False
// wrap with array to prevent args distributing
export type IsNever<T, True, False = never> = [T] extends [never]
  ? True
  : False;

// return True if T is `any`, otherwise return False
export type IsAny<T, True, False = never> = (
  | True
  | False) extends (T extends never ? True : False)
  ? True
  : False;

// return True if T is `unknown`, otherwise return False
export type IsUnknown<T, True, False = never> = unknown extends T
  ? IsAny<T, False, True>
  : False;

// return True if T strictly includes U, otherwise return False
export type StrictlyIncludes<T, U, True, False = never> = Exclude<
  U,
  T
> extends never
  ? (IsAny<T, 1, 0> extends 1
      ? True
      : (IsAny<U, 1, 0> extends 1
          ? False
          : (IsUnknown<T, 1, 0> extends 1 ? IsUnknown<U, True, False> : True)))
  : False;

// tests and returns True if they are equal, False otherwise.
// wrap with array and do both ways to prevent args distrubition
export type AreStrictlyEqual<T, U, True, False = never> = StrictlyIncludes<
  T,
  U,
  1,
  0
> extends 1
  ? StrictlyIncludes<U, T, True, False>
  : False;

// tests and returns True if both objects have same keys, False otherwise.
export type HaveSameKeys<T, U, True, False = never> = (
  | Exclude<keyof T, keyof U>
  | Exclude<keyof U, keyof T>) extends never
  ? True
  : False;

// https://github.com/Microsoft/TypeScript/issues/26051
export type Exact<T, X extends T> = T &
  { [K in keyof X]: K extends keyof T ? X[K] : never };
// U extends Exact<{ [K in keyof T]-?: (v: T[K]) => any }, U>

Contribute

Pull Requests are welcome!
Just try to be consistent with existing naming conventions and coding styles.
Names must be concise, easy to read, and precisely descriptive.
I've setup prettier, so make sure your codes are auto formatted according to my prettier setup.

License

MIT License

More Repositories

1

tscpaths

Replace absolute paths to relative paths after typescript compilation
TypeScript
266
star
2

react-native-google-sign-in

React Native Wrapper for Latest Google Sign-In OAuth SDK / API
Objective-C
211
star
3

graphql-rule

GraphQL rule / access control / auth / security / authorization / permission
JavaScript
157
star
4

graphql-input-number

A configurable custom input number type for GraphQL with sanitization and validation.
JavaScript
101
star
5

react-native-linkedin-sdk

React Native Wrapper for Latest LinkedIn Mobile SDK for Sign-In / Auth and API Access.
Objective-C
40
star
6

batchloader

BatchLoader is a utility for data fetching layer to reduce requests via batching written in TypeScript. Inspired by Facebook's DataLoader. Works great with GraphQL, MongoDB, Mongoose, etc.
TypeScript
35
star
7

firebase-encode

Encode and decode firebase key string to escape and unescape unsafe characters (.$[]#/).
JavaScript
34
star
8

proptypes-parser

PropTypes parser / generator for React and React Native components with GraphQL-like syntax.
JavaScript
29
star
9

react-native-mail-compose

React Native library for composing email. Wraps MFMailComposeViewController for iOS and Intent for Android.
Java
27
star
10

react-native-message-compose

React Native library for composing Message / SMS / Text. Wraps MFMessageComposeViewController for iOS and Intent for Android.
Java
24
star
11

graphql-scalar

Configurable custom GraphQL Scalars (string, number, date, etc) with sanitization / validation / transformation in TypeScript.
TypeScript
23
star
12

vcard-generator

VCard v4.0 rfc6350 compliant generator from JSON.
JavaScript
21
star
13

graphql-input-string

A configurable custom input string type for GraphQL with sanitization and validation.
JavaScript
20
star
14

graphql-relay-connection

A GraphQL Relay connection with cursor based on any comparator. Can be used with ObjectId for MongoDB.
JavaScript
20
star
15

seri

JavaScript (Node.js) serializer / deserializer with support for classes.
JavaScript
19
star
16

tsapis

Various cloud services API response types documented and written in TypeScript
TypeScript
16
star
17

country-calling-code

Country calling codes based on countrycode.org
JavaScript
15
star
18

react-native-router-relay-todo

React Native Todo App with react-router-native and relay
JavaScript
10
star
19

auth0-react-native

React Native port of Auth0 SDK (auth0/auth0.js)
JavaScript
10
star
20

react-hat

A higher order component for react-helmet that auto fills favicon, og, twitter meta tags for SEO.
JavaScript
9
star
21

s3-policy-v4

Amazon AWS S3 Upload Policy Generator with Signature Version 4
JavaScript
8
star
22

angular-smart-scroll

Smart infinite scroll directive for Angular.js that is customizable to support nested, horizontal, vertical, and/or bidirectional scrolls
JavaScript
7
star
23

underscore-node

Underscore for Node.js without unnecessary cross-browser checks
JavaScript
7
star
24

romodel

A lightweight and unopinionated model-based data accessor / enhancer library
JavaScript
6
star
25

ts-jutil

TypeScript library of simple utility functions
TypeScript
6
star
26

graphql-fetcher

A GraphQL data fetcher using fetch API.
JavaScript
5
star
27

iso-country-codes

ISO Country Codes including Alpha-2, Alpha-3, and numeric codes
JavaScript
5
star
28

jexgrid

JavaScript Grid Solution
JavaScript
4
star
29

react-native-contact-picker

React Native wrapper for CNContactPickerViewController
Swift
4
star
30

rn-json-store

A thin wrapper around React Native's AsyncStorage to easily write and read JSON values.
JavaScript
4
star
31

graphql-complexity

Compute complexity of GraphQL Queries
JavaScript
3
star
32

basex-encoder

Encode / decode any base X to and from string or buffer written in TypeScript
TypeScript
3
star
33

jwt-node-decoder

Decodes JWT (JSON Web Token) and checks expiration date. A Node port of angular-jwt.
JavaScript
2
star
34

auth-perm

A simple level-based permission / authorization / access control
JavaScript
2
star
35

angular-facebook-api

A Facebook SDK wrapper service for Angular.js
JavaScript
2
star
36

fullcontact-card-reader

FullContact Card Reader API Wrapper for Node.js
JavaScript
2
star
37

firestore-backup-cronjob

TypeScript
2
star
38

s3-policy-middleware

Express Middleware for Amazon AWS S3 Upload Policy Generator with Signature Version 4
JavaScript
2
star
39

servertil

HTTP server / express related utilities library written in TypeScript
TypeScript
1
star
40

material-design-color-palette

Material design color palette meets TinyColor
JavaScript
1
star
41

tsxhr

A super lightweight XMLHTTPRequest wrapper written in TypeScript. No dependencies.
TypeScript
1
star
42

healthcheck-ok

A simple healthcheck middleware for express.js that sends 200.
JavaScript
1
star
43

tstf

CLI tools for useful TypeScript code transformations such as paths transforms.
TypeScript
1
star
44

restpi

REST API client for various third party cloud services
TypeScript
1
star
45

superwild

Extremely fast, optimized, compilable wildcard pattern matching without using RegExp, which is slow.
TypeScript
1
star
46

webtil

Tiny utility library functions to be used in browser written in TypeScript
TypeScript
1
star
47

sanidator

Sanitize and Validate JavaScript Objects
JavaScript
1
star
48

unagi

A collection of basic JavaScript utility functions intended for Node.js (V8). It is best optimized for performance with NO cross-browser compatibility.
JavaScript
1
star
49

formost

Event based reactive form field model
TypeScript
1
star
50

react-native-add-contact

WIP: NOT WORKING YET! Add contact to address book
Java
1
star
51

vcard3

vCard 3.0 iOS compliant
TypeScript
1
star
52

react-native-issues-solutions

This repo is for me to track current React Native issues and possible/best available solutions.
1
star
53

firestore-model

Firestore / Firebase object model schema wrapper
TypeScript
1
star
54

expjson

Super lightweight, fast, and optimized evaluate-able and compilable expressions in JSON written in TypeScript
TypeScript
1
star
55

ga-util

Google Analytics Wrapper written in TypeScript
TypeScript
1
star
56

ts-url

URL object parser written in TypeScript
TypeScript
1
star
57

brands

social media brands / branding resources
1
star
58

tshttpcode

HTTP Status Code enum in TypeScript optimized for tree shaking
TypeScript
1
star
59

swifty-js

Swift like property observer (willSet, didSet) pattern for JavaScript.
JavaScript
1
star
60

memprop

React optimization tool for memoizing (function / object) property to avoid unnecessary re-renders
TypeScript
1
star
61

blitline-s3

Post Blitline jobs that uploads to s3 and do polling for the jobs.
JavaScript
1
star
62

notil

Small utility library written in TypeScript to be used in Node.js environment using Node packages.
TypeScript
1
star
63

smartystreets-js

JS client for SmartyStreets API. Address autocomplete and verification.
JavaScript
1
star