Rtype
Intuitive structural type notation for JavaScript.
Install / Use
/learn @ericelliott/RtypeREADME
Rtype
Intuitive structural type notation for JavaScript.
(parameterName: Type) => ReturnType
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
Table of Contents
- About Rtype
- Reading Function Signatures
- Interface: User Defined Types
- Composing Types
- Event Emitters
- Comments
- References
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
nullis part ofAnyand is not covered byObject. If you want to allownullwithObject, you must specify the union explicitly:Object | null- the
Functionbuiltin 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 syno
Related Skills
node-connect
328.7kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
81.0kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
328.7kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
81.0kCommit, push, and open a PR
