• Stars
    star
    1,129
  • Rank 41,225 (Top 0.9 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated almost 6 years ago

Reviews

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

Repository Details

Intuitive structural type notation for JavaScript.

Rtype

Join the chat at https://gitter.im/ericelliott/rtype

Intuitive structural type notation for JavaScript.

(parameterName: Type) => ReturnType

Table of Contents

About Rtype

  • Great for simple documentation.
  • Compiler-agnostic type notation - for use with ECMAScript standard tools.
  • Low learning curve for JavaScript developers.
  • Can embed in JS as strings, for example with rfx for easy runtime reflection.
  • Standing on the shoulders of giants. Inspired by: ES6, TypeScript, Haskell, Flow, & React

What is Rtype?

Rtype is a JS-native representation of structural type interfaces with a TypeScript-inspired notation that's great for documentation.

Status: RFC

Developer preview. Please comment.

Currently in-use for production library API documentation, but breaking changes are expected.

In the future, libraries may parse rtype strings and return predicate functions for runtime type checking. Static analysis tools are also possible, but no significant developer tooling is currently available. Feel free to build some!

Why?

Perhaps the most important part of API documentation is to quickly grasp the function signatures and data structures required to work with the API. There are existing standards for this stuff, but we think we can improve on them:

  • JSDoc is too verbose, not intuitive, and painful to maintain.
  • TypeScript's structural types are very appealing, but opting into TypeScript's JS superset and runtime limitations is not.

We want a type representation that is very clear to modern JavaScript developers (ES2015+), that could potentially be used at runtime with simple utilities.

Why Not Just Use TypeScript?

We want the best of all worlds:

  • An intuitive way to describe interfaces for the purposes of documentation, particularly function signatures.
  • Runtime accessible type reflection (even in production) with optional runtime type checks that can be disabled in production (like React.PropTypes). See rfx.
  • A way to specify types in standard ES2015+ code. Use any standard JS compiler. See rfx.
  • An easy way to generate interface documentation (like JSDoc).

TypeScript is great for compile-time and IDE features, and you could conceivably generate docs with it, but runtime features are lacking. For example, I want the ability to query function signatures inside the program at runtime, along with the ability to turn runtime type checking on and off. AFAIK, that's not possible with TypeScript (yet - there is experimental runtime support using experimental features of the ESNext Reflect API).

Reading Function Signatures

Function types are described by a function signature. The function signature tells you each parameter and its type, separated by a colon, and the corresponding return type:

(param: Type) => ReturnType

To make the signature familiar to readers, we use common JavaScript idioms such as destructuring, defaults, and rest parameters:

(...args: [...String]) => Any
({ count = 0: Number }) => Any

If a parameter or property has a default value, most built-in types can be inferred:

({ count = 0 }) => Any

If the type is a union or Any, it must be specified:

({ collection = []: Array | Object }) => Any

Optionally, you may name the return value, similar to named parameters:

(param: Type) => name: Type

Or even name a signature to reuse it later on:

connect(options: Object) => connection: Object

Optional Parameters

Optional parameters can be indicated with ?:

(param: Type, optParam?: Type) => ReturnType

Anonymous Parameters

Parameter names can be omitted:

is(Any) => Boolean

In the case of an anonymous optional parameter the type must be prefixed by ?::

toggle(String, ?: Boolean) => Boolean

In the case of an anonymous rest parameter, simply omit the name:

(...: [...Any]) => Array

Type Variables

Type variables are types that do not need to be declared in advance. They may represent any type, but a single type variable may only represent one type at a time in the scope of the signature being declared.

The signature for double is usually thought of like this:

double(x: Number) => Number

But what if we want it to accept objects as well?

const one = {
  name: 'One',
  valueOf: () => 1
};

double(one); // 2

In that case, we'll need to change the signature to use a type variable:

double(x: n) => Number

By convention, type variables are single letters and lowercased in order to visually distinguish them from predefined types. That way the reader doesn't need to scan back through documentation looking for a type declaration where there is no type declaration to be found.

Reserved Types

Builtin Types

Array, Boolean, Function, Number, Object, RegExp, String, Symbol
ArrayBuffer, Date, Error, Map, Promise, Proxy, Set, WeakMap, WeakSet
Notes
  • null is part of Any and is not covered by Object. If you want to allow null with Object, you must specify the union explicitly: Object | null
  • the Function builtin type expands to (...args: [...Any]) => Any

The Any Type

The special type Any means that any type is allowed:

(...args: [...Any]) => Array

The Void Type

The special type Void should only be used to indicate that a function returns no meaningful value (i.e., undefined). Since Void is the default return type, it can be optionally omitted. Nevertheless Void return types should usually be explicitly annotated to denote function side-effects.

set(name: String, value: String) => Void

Is equivalent to:

set(name: String, value: String)

The Predicate Type

The special type Predicate is a function with the following signature:

(...args: [...Any]) => Boolean

The Iterable Type

Arrays, typed arrays, strings, maps and sets are iterable. Additionally any object that implements the @@iterator method can be iterated.

(paramName: Iterable) => Void

Is equivalent to

interface Iterator {
  next() => {
    done: Boolean,
    value?: Any
  }
}

interface IterableObject {
  [Symbol.iterator]: () => Iterator
}

(paramName: IterableObject) => Void

The TypedArray Type

It covers these contructors: Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array.

Literal Types

Literals are also accepted as types.

signatureName(param1: String, param2: 'value1' | 'value2' | 'value3') => -1 | 0 | 1

Tuples

The type of arrays' elements can also be specified:

// an array that contains exactly 2 elements
[Number, String]

For βˆ… or more and 1 or more element(s) of the same type you can use the rest operator like so:

// 0 or more
[...Number]

// 1 or more
[Number...]
//which is equivalent to
[Number, ...Number]

Union Types

Union types are denoted with the pipe symbol, |:

(userInput: String | Number) => String | Number

Negated Types

It is sometime easier and more informative to delimit a type by defining what it's not. The negation operator lets you exclude by substracting from Any.

JSON::parse(String, reviver: Function)
  => Boolean | Number | String | Object | Array | null,
  throws SyntaxError

// is less concise than

JSON::parse(String, reviver: Function)
  => !Function & !Void & !Symbol,
  throws SyntaxError

// which is equivalent to

JSON::parse(String, reviver: Function)
  => !(Function | Void | Symbol),
  throws SyntaxError

Constructors

Constructors in JavaScript require the new keyword. You can identify a constructor signature using the new keyword as if you were demonstrating usage:

new User({ username: String }) => UserInstance

In JavaScript, a class or constructor is not synonymous with an interface. The class or constructor definition describe the function signature to create the object instances. A separate signature is needed to describe the instances created by the function. For that, use a separate interface with a different name:

interface UserInstance {
  username: String,
  credentials: String
}

Accessor Descriptors

An accessor function is defined by prefixing a method with get or set.

new User({ username: String }) => {
  username: String,
  get name() => String,
  set name(newName: String) // return type defaults to Void
}

Throwing Functions

To indicate that a function can throw an error you can use the throws keyword.

(paramName: Type) => Type, throws: TypeError | DOMException

For the generic Error type, you can optionally omit the throw type:

(paramName: Type) => Type, throws

Is equivalent to:

(paramName: Type) => Type, throws: Error

Dependencies

You can optionally list your functions' dependencies. In the future, add-on tools may automatically scan your functions and list dependencies for you, which could be useful for documentation and to identify polyfill requirements.

// one dependency
signatureName() => Type, requires: functionA

// several dependencies
signatureName()
  => Type,
  requires: functionA, functionB

Interface: User Defined Types

You can create your own types using the interface keyword.

An interface can spell out the structure of an object:

interface UserProfile {
  name: String,
  avatarUrl?: Url,
  about?: String
}

Interfaces support builtin literal types:

interface UserInstance {
  name: /\w+/,
  description?: '',
  friends?: [],
  profile?: {}
}

A one-line interface doesn't need brackets:

interface Name: /\w+/

Function Interface

A regular function signature is a shorthand for a function interface:

user({ name: String, avatarUrl?: Url }) => UserInstance

A function interface must have a function signature:

interface user {
  ({ name: String,  avatarUrl?: Url }) => UserInstance
}

For polymorphic functions, use multiple function signatures:

interface Collection {
  (items: [...Array]) => [...Array],
  (items: [...Object]) => [...Object]
}

If all signatures return/emit/throw/require the same thing, you can consolidate this information in one place:

interface Bar {
  (String, Object),
  (String, Boolean)
} => Void

Note that named function signatures in an interface block indicate methods, rather than additional function signatures:

interface Collection {
  (signatureParam: Any) => Any,              // Collection() signature
  method1(items: [...Array]) => [...Array],  // method
  method2(items: [...Object]) => [...Object] // method
}

For convenience you can inline overloaded methods directly inside a function interface.

interface Foo {
  (Type) => Type,

  a(Object) => Void,
  a(String, Number) => Void,

  b(Object) => Void,
  b(String, Number) => Void
}

Here is the equivalent using separate interfaces:

interface a {
  (Object) => Void,
  (String, Number) => Void
}

interface b {
  (Object) => Void,
  (String, Number) => Void
}

interface Foo {
  (Type) => Type,

  a,
  b
}

this Binding

Sometimes you want to define the shape of the call-site of a function; the :: operator lets you do just that, granted that you have declared the newly bound interface.
For convenience let's reuse the previously defined IterableObject interface:

// IterableObject::head() => Any, throws: TypeError
const head = function () {
  const [first] = this;
  return first;
};

head.call([1,2,3]); // 1

Dynamic Property Keys

Dynamic properties may be labeled and typed. If omitted, the type defaults to String.

{
  [id1]: {
    skating: {time: 1000, money: 300},
    'cooking': {time: 9999, money: 999}
  },
  [id2]: {
    "jogging": {time: 300, money: 0}
  }
  // etc...
}

The preceding object can be expressed using these interfaces:

interface Expenditure {
  time: Number,
  money: Number
}

interface clientHobbies {
  [id: Symbol]: {
    // The following:
    [hobby]: Expenditure
    // is equivalent to
    // [hobby: String]: Expenditure
  }
}

Predicate Literals

Interfaces may use predicate literals, terminated by a semicolon:

interface Integer (number) => number === parseInt(number, 10);

You can combine predicate literals with interface blocks. Semicolon disambiguates:

interface EnhancedInteger (number) => number === parseInt(number, 10); {
  isDivisibleBy3() => Boolean,
  double() => Number
}

Multi-line example:

interface EnhancedInteger (number) => {
  return number === parseInt(number, 10);
}; {
  isDivisibleBy3() => Boolean,
  double() => Number
}

Composing Types

Whenever you want to compose an interface out of several others, use the spread operator for that:

interface Person {
  name: Name,
  birthDate: Number
}

interface User {
  username: String,
  description?: String,
  kudos = 0: Number
}

interface HumanUser {
  ...Person,
  ...User,
  avatarUrl: String
}

You can also use the spread inside object type literals:

interface Company {
  name: Name,
  owner: { ...Person, shareStake: Number }
}

In case of a name conflict, properties with same names are merged. It means all prerequisites must be satisfied. It’s fine to make types more specific through type literals:

interface Creature {
  name: String,
  character: String,
  strength: (number) => (number >= 0 && number <= 100)
}

interface Human {
  ...Creature,
  name: /^(.* )?[A-Z][a-z]+$/,
  character: 'friendly' | 'grumpy'
}

To make sure we can run a static type check for you, we don’t allow merging two different literals. So this would result in a compile error:

// Invalid!
interface Professor {
  ...Human,
  name: /^prof\. \w+$/
}

Obviously, merging incompatible interfaces is also invalid:

// Invalid!
interface Bot {
  ...Creature,
  name: Number
}

Event Emitters

When composing an observable interface, you can use the emits keyword to describe the events it emits:

interface Channel {
  ...EventEmitter
} emits: {
  'messageAdded': (body: String, authorId: Number),
  'memberJoined': (id: Number, { name: String, email: String })
}

// this is equivalent

interface Channel {
  ...EventEmitter
} emits: {
  messageAdded(body: String, authorId: Number),
  memberJoined(id: Number, { name: String, email: String })
}

Comments

Standard JS comment syntax applies, e.g.:

// A single-line comment, can appear at the end of a line.

/*
  A multi-line comment.
  Can span many lines.
*/

References

Somewhat related ideas and inspiration sources.

More Repositories

1

react-pure-component-starter

A pure component dev starter kit for React.
JavaScript
792
star
2

autodux

Automate the Redux boilerplate.
JavaScript
592
star
3

h5Validate

An HTML5 form validation plugin for jQuery. Works on all major browsers, both new and old. Implements inline, realtime validation best practices (based on surveys and usability studies). Developed for production use in e-commerce. Currently in production with millions of users.
JavaScript
577
star
4

moneysafe

Convenient, safe money calculations in JS
JavaScript
452
star
5

credential

Easy password hashing and verification in Node. Protects against brute force, rainbow tables, and timing attacks.
JavaScript
348
star
6

rfx

Self documenting runtime interfaces.
JavaScript
277
star
7

redux-dsm

Declarative state machines for Redux: Reduce your async-state boilerplate.
JavaScript
222
star
8

speculation

JavaScript promises are made to be broken. Speculations are cancellable promises.
JavaScript
197
star
9

irecord

An immutable store that exposes an RxJS observable. Great for React.
JavaScript
192
star
10

the-software-developers-library

The Software Developer's Library: a treasure trove of books for people who love code. Curated by Eric Elliott
192
star
11

react-things

A exploratory list of React ecosystem solutions
174
star
12

express-error-handler

A graceful error handler for Express and Restify applications.
JavaScript
168
star
13

feature-toggle

A painless feature toggle system in JavaScript. Decouple development and deployment.
JavaScript
155
star
14

ogen

Write synchronous looking code & mix synchronous & asynchronous results using generators & observables.
JavaScript
129
star
15

tdd-es6-react

Examples of TDD in ES6 with React
95
star
16

react-hello

A hello world example React app
JavaScript
63
star
17

fluentjs1

Talk - Fluent JavaScript Part 1: Prototypal OO. Learn to code like a JS native. Take advantage of JavaScript's distinguishing features in order to write better code.
JavaScript
53
star
18

neurolib

Neuron emulation tools
JavaScript
52
star
19

the-two-pillars-of-javascript-talk

References from "The Two Pillars of JavaScript" talk
51
star
20

maybearray

Native JavaScript Maybes built with arrays.
JavaScript
49
star
21

qconf

Painless configuration with defaults file, environment variables, arguments, function parameters.
JavaScript
45
star
22

object-list

Treat arrays of objects like a db you can query.
JavaScript
43
star
23

gql-validate

Validate a JS object against a GraphQL schema
JavaScript
33
star
24

bunyan-request-logger

Automated request logging middleware for Express. Powered by Bunyan.
JavaScript
29
star
25

tinyapp

A minimal, modular, client-side application framework.
JavaScript
28
star
26

arraygen

Turn any array into a generator.
JavaScript
28
star
27

dpath

Dot Path - FP sugar for immutables
JavaScript
22
star
28

rootrequire

npm install --save rootrequire # then `var root = require('rootrequire'), myLib = require(root + '/path/to/lib.js');`
JavaScript
19
star
29

siren-resource

Resourceful routing with siren+json hypermedia for Express.
JavaScript
18
star
30

version-healthcheck

A plug-and-play /version route for the Node.js Express framework.
JavaScript
17
star
31

react-easy-universal

Universal Routing & Rendering with React & Redux was too hard. Now it's easy.
JavaScript
16
star
32

odotjs

A prototypal OO library for JavaScript
JavaScript
13
star
33

todotasks

TodoMVC for task runners. Not sure which task runner to use? Take a look at some reference implementations.
JavaScript
12
star
34

react-test-demo

React Test Demo
CSS
12
star
35

react-faves

Favorite React Tools
12
star
36

jiron

Make your API self documenting and your clients adaptable to API changes.
11
star
37

saas-questions

SaaS Questions: The most important questions every SaaS company should have answers to.
10
star
38

applitude

JavaScript application namespacing and module management.
JavaScript
8
star
39

grange

Generate all sorts of values based on a range of numbers.
JavaScript
7
star
40

talks-and-interviews

A list of my talks and interviews.
7
star
41

tinyerror

Easy custom errors in browsers, Node, and Applitude
JavaScript
7
star
42

jQuery.outerHTML

A tiny outerHTML shim for jQuery
JavaScript
6
star
43

connect-cache-control

Connect middleware to prevent the browser from caching the response.
JavaScript
6
star
44

nfdata

NFData - A metadata proposal for NFT interoperability
5
star
45

xforms

xforms
JavaScript
5
star
46

sparkly

Ignite Learning, Inspire Creation
CSS
5
star
47

clctr

Event emitting collections with iterators (like Backbone.Collection).
JavaScript
3
star
48

ofilter

Array.prototype.filter for objects.
JavaScript
3
star
49

rejection

You gotta lose to win.
JavaScript
3
star
50

colab

A project collaboration platform centered on live video streaming and monetization.
CSS
3
star
51

slides-intro-to-js-objects

A basic (and short) overview of objects in JavaScript.
JavaScript
2
star
52

slides-modular-javascript

Modular JavaScript With npm and Node Modules
CoffeeScript
2
star
53

testling-jasmine

run jasmine tests in all the browsers with testling
JavaScript
2
star
54

hifi

Flow based programming for Node services.
1
star
55

resource-acl

An ACL intended for use with express-resource.
1
star
56

pja-guestlist-client

The browser client for Guestlist. A demo app for Programming JavaScript Applications.
JavaScript
1
star
57

course-primer

A primer for the "Learn JavaScript with Eric Elliott" course series. Prerequisite for all courses.
1
star
58

mapall

Given an array of promises, map to a same-ordered array of resolutions or rejections.
1
star
59

pja-sections

Draft sections for "Programming JavaScript Applications"
1
star
60

maybe-assign

Like Object.assign, but skip null or undefined props.
1
star