Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

simplytyped

Package Overview
Dependencies
Maintainers
1
Versions
52
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

simplytyped

yet another Typescript type library for advanced types

  • 1.1.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
7.8K
increased by1.09%
Maintainers
1
Weekly downloads
 
Created
Source

SimplyTyped

Greenkeeper badge

Build Status

Yet another typing library. This differs by aiming to be less experimental than others, driven by industry use cases.

Many of the exposed types are a very thin layer above built in functionality. The goal is to provide all of the building blocks necessary to make concise, yet complex types.

npm install --save-dev simplytyped

Conditionals

If - And - Or - Not - Xor - Nand

Predicates

IsAny - IsArray - IsBoolean - IsFunction - IsNever - IsNumber - IsObject - IsType

Objects

Keys - ObjectType - CombineObjects - Intersect - SharedKeys - DiffKeys - AllKeys - Omit - Merge - Overwrite - DeepPartial - DeepReadonly - Optional - GetKey - AllRequired - Required - TaggedObject

Tuples

Tuple - UnionizeTuple - IntersectTuple - Length

Strings

Diff - StringEqual - DropString

Numbers

IsZero - IsOne - NumberToString - Next - Prev - Add - Sub - NumberEqual

Functions

Predicate - ConstructorFunction - AnyFunc - Readonly - isKeyOf - objectKeys

Utils

Nullable - NoInfer - Unknown - Nominal

Conditionals

Some (somewhat common) implementations of conditional type logic

If

type x = If<True, string, number> // => string
type y = If<False, string, number> // => number

And

type x = If<And<True, True>, string, number> // => string
type y = If<And<True, False>, string, number> // => number
...

Or

type x = If<Or<True, False>, string, number> // => string
type y = If<Or<False, False>, string, number> // => number
...

Not

type x = Not<True> // => False
type y = Not<False> // => True

Xor

type x = Xor<True, False> // => True
type y = Xor<True, True> // => False
...

Nand

type x = Nand<True, True> // => False
type y = Nand<False, True> // => True

Predicates

IsAny

type x = IsAny<any> // => True
type y = IsAny<'hey'> // => False

IsArray

type x = IsArray<any[]> // => True
type y = IsArray<number> // => False

IsBoolean

type x = IsBoolean<false> // => True
type y = IsBoolean<3> // => False

IsFunction

type x = IsFunction<(() => string)> // => True
type y = IsFunction<'not a function'> // => False

IsNever

Returns true if type is never, otherwise returns false.

type x = IsNever<'hi'> // => False
type y = IsNever<never> // => True

IsNumber

type x = IsNumber<3> // => True
type y = IsNumber<false> // => False

IsObject

type x = IsObject<{a: number, b: string}> // => True
type y = IsObject<string> // => False

IsType

Given a base type and a value, check to see if value matches the base type. Useful for checking if something is an instance of a class.

class Thing { x: string };
type x = IsType<Thing, { x: string }> // => True
type y = IsType<Thing, { y: number }> // => False

Objects

type obj1 = { w: string, x: string, y: number }
type obj2 = { y: string, z: number }

Keys

No different than keyof, but can look a bit nicer when nesting many types deep

type x = keyof obj1 // => 'w' | 'x' | 'y'
type y = Keys<obj1> // => 'w' | 'x' | 'y'

ObjectType

On its own, not that interesting. Takes an object and makes it an object type. Is useful when combined with & intersection types (as seen next).

type x = ObjectType<obj1> // => { w: string, x: string, y: number }

CombineObjects

Takes the intersection between two objects, and flattens them. This can make extremely complex types look much nicer.

type x = obj1 & obj2 // => { w: string, x: string, y: number } & { y: string, z: number }
type y = CombineObjects<obj1, obj2> // => { w: string, x: string, y: string & number, z: number }

Intersect

Returns only the shared properties between two objects. All shared properties must be the same type.

type x = Intersect<obj1, { x: string }> // => { x: string }

SharedKeys

Gets all of the keys that are shared between two objects (as in keys in common).

type x = SharedKeys<obj1, obj2> // => 'y'

DiffKeys

Gets all of the keys that are different from obj1 to obj2.

type x = DiffKeys<obj1, obj2> // => 'w' | 'x'
type y = DiffKeys<obj2, obj1> // => 'z'

AllKeys

Gets all keys between two objects.

type x = AllKeys<obj1, obj2> // => 'w' | 'x' | 'y' | 'z'

Omit

Gives back an object with listed keys removed.

type x = Omit<obj1, 'w' | 'x'> // => { y: number }

Merge

Much like _.merge in javascript, this returns an object with all keys present between both objects, but conflicts resolved by rightmost object.

type x = Merge<obj1, obj2> // => { w: string, x: string, y: string, z: number }

Overwrite

Can change the types of properties on an object. This is similar to Merge, except that it will not add previously non-existent properties to the object.

type a = Overwrite<obj1, obj2> // => { w: string, x: string, y: string }
type b = Overwrite<obj2, obj1> // => { y: number, z: number }

DeepPartial

Uses Partial to make every parameter of an object optional (| undefined).

type x = DeepPartial<obj1> // => { w?: string, x?: string, y?: number }

DeepReadonly

Uses Readonly to make every parameter of an object readonly

type x = DeepReadonly<obj1> // => { w: readonly string, x: readonly string, y: readonly number }

Optional

Makes certain properties on an object optional.

type x = Optional<obj1, 'w' | 'x'> // => { w?: string, x?: string, y: number }

GetKey

Gets the value of specified property on any object without compile time error (Property 'b' does not exist on type '{ a: string; }'.) and the like. Returns never if the key is not on the object. I suggest using If<HasKey... first to handle validity of the object first.

type x = GetKey<{ a: string }, 'a'> // => string
type y = GetKey<{ a: string }, 'b'> // => never

ConstructorFor

Builds the type of a constructor function for a particular object.

type c = ConstructorFor<obj1> // => new (...args: any[]) => { w: string, x: string, z: number }

AllRequired

Makes all fields of an object "required". This means not Nullable and not optional.

type x = { a?: string, b: number | undefined };
type o = AllRequired<x>; // => { a: string, b: number }

Required

Makes certain fields of an object "required"

type x = { a?: string, b: number | undefined };
type o = Required<x, 'a'>; // => { a: string, b: number | undefined }

TaggedObject

Creates an object with each entry being tagged by the key defining that entry.

const obj = {
    a: { merp: 'hi' },
    b: { merp: 'there' },
    c: { merp: 'friend' },
};

const got = taggedObject(obj, 'name');
/*
got = {
    a: { name: 'a', merp: 'hi' },
    b: { name: 'b', merp: 'there' },
    c: { name: 'c', merp: 'friend' },
};
*/

Utils

A few utility functions that generically work in any context, with any type.

Nullable

Makes a type nullable (null | undefined).

type x = Nullable<string>; // => string | null | undefined

NoInfer

Prevents typescript from being able to infer a generic type. Useful when trying to get a function to infer based on one argument of a function, but not another.

function doStuff<T>(x: T, y: NoInfer<T>): T { return x; }
function inferAll<T>(x: T, y: T): T { return x; }
doStuff('hi', 'there') // => compile error
inferAll('hi', 'there') // => typeof T === 'string'

Unknown

A type that has no properties and cannot be passed into functions. This is particularly useful on the boundaries of an app where you may not know the type of a variable. For instance JSON.parse could return an Unknown and would require validation and / or a type assertion to make it a useful type.

declare let x: Unknown;
x = 'hi'; // valid operation
function doStuff(a: number) {}
doStuff(x); // invalid operation
x.thing // invalid operation
x() // invalid operation

Nominal

This creates a type that, while it shares all of the properties with its parent type, cannot be set to another type without containing the same tag. This is useful in the case where you have a string that is an id, but you don't want to be able to set just any string to this id; only a string tagged as being an id.

type Id = Nominal<string, 'id'>; // => string
declare let x: Id;
x = 'hi'; // invalid operation;
x = 'hi' as Nominal<string, 'id'>; // valid operation
x = 'hi' as Id; // valid operation

Tuples

A tuple can be defined in two ways: [number, string] which as of Typescript 2.7 has an enforced length type parameter: [number, string]['length'] === 2 or using this library's Tuple<any> which can be extended with any length of tuple: function doStuff<T extends Tuple<any>>(x: T) {}.

Tuple

function doStuff<T extends Tuple<any>>(x: T) {}

doStuff(['hi', 'there']); // => doStuff(x: ['hi', 'there']): void

UnionizeTuple

Returns elements within a tuple as a union.

type x = UnionizeTuple<[number, string]> // => number | string

IntersectTuple

Returns elements of a tuple intersected with each other. Note: only works for tuples up to length 10

type x = IntersectTuple<[{a: 'hi'}, {b: 'there'}]>; // => {a: 'hi'} & {b: 'there'}

Length

Gets the length of either a built-in tuple, or a Vector. This will only work after Typescript 2.7 is released.

type x = Length<['hey', 'there']> // => 2

Strings

Diff

Get the differences between two unions of strings.

type x = Diff<'hi' | 'there', 'hi' | 'friend'> // => 'there'

StringEqual

Returns true if all elements in two unions of strings are equal.

type x = StringEqual<'hi' | 'there', 'hi'> // => False
type y = StringEqual<'hi' | 'there', 'there' | 'hi'> // => True

DropString

Can remove a string from a union of strings

type x = DropString<'hi' | 'there', 'hi'> // => 'there'

Numbers

Supports numbers from [0, 63]. More slows down the compiler to a crawl right now.

IsZero

Returns true if the number is equal to zero.

type x = IsZero<1> // => False
type y = IsZero<0> // => True

IsOne

Returns true if the number is equal to one.

type x = IsOne<0> // => False
type y = IsOne<1> // => True

NumberToString

Returns the string type for a given number

type x = NumberToString<0> // => '0'
type y = NumberToString<1> // => '1'

Next

Returns the number + 1.

type x = Next<0> // => 1
type y = Next<22> // => 23

Prev

Returns the number - 1.

type x = Prev<0> // => -1
type y = Prev<23> // => 22

Add

Adds two numbers together.

type x = Add<22, 8> // => 30

Sub

Subtracts the second from the first.

type x = Sub<22, 8> // => 14

NumberEqual

Returns True if the numbers are equivalent

type x = NumberEqual<0, 0> // => True
type y = NumberEqual<22, 21> // => False

Functions

Predicate

This is a function that takes some args and returns a boolean

type x = Predicate // => (...args: any[]) => boolean
const isThing: Predicate = (x: Thing) => x instanceof Thing;

ConstructorFunction

This represents the constructor for a particular object.

class Thing { constructor(public x: string) {}}
type x = ConstructorFunction<Thing>
declare const construct: x;
const y = new construct(); // => y instanceof Thing

AnyFunc

Concisely and cleanly define an arbitrary function. Useful when designing many api's that don't care what function they take in, they just need to know what it returns.

type got = AnyFunc; // => (...args: any[]) => any;
type got2 = AnyFunc<number>; // => (...args: any[]) => number;

Readonly

This takes a runtime object and makes its properties readonly. Useful for declare object literals, but using inferred types.

const config = Readonly({
    url: 'https://example.com',
    password: 'immasecurepassword',
}); // => { url: readonly string, password: readonly string }

isKeyOf

Type guard returning true if k is a key in obj.

const obj = { a: '' };
const k = 'a';
if (isKeyOf(obj, k)) {
    obj[k] = 'hi'; // typeof k === 'a'
} else {
    throw new Error('oops'); // typeof k === string
}

objectKeys

Same as Object.keys except that the returned type is an array of keys of the object. Note that for the same reason that Object.keys does not do this natively, this method is not safe for objects on the perimeter of your code (user input, read in files, network requests etc.).

const obj = { a: '', b: 22 };
const keys = objectKeys(obj); // Array<'a' | 'b'>

Keywords

FAQs

Package last updated on 03 May 2018

Did you know?

Socket

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc