ts-optional
In TypeScript, like in JavaScript, every value is nullable. However, sometimes you want to prevent the caller from sending a null value. You might end up with something like this:
However, sometimes a null
value is valid and expected. There is no way to enforce this in
TypeScript, so you would resort to a comment:
// Returns null if the source string is not a valid number
With this library, optional values are explicit and enforced by the TypeScript compiler. All you
need to do is start using nil
instead of null
, and annotating optional values with Optional
.
Installation
> npm install --save ts-optional
Optionals are attached to the global object and uses Monkey Patching to extend the behaviour of
the global Object prototype. Depending on your platform you must execute the index.js
file before
running the TypeScript code.
Directly in a script tag
Where the TypeScript source file would contain
/// <reference path="node_modules/ts-optional/index.d.ts" />
.
Using Node or Browserify (CommonJS)
Put this in the head of the TypeScript source file.
/// require"ts-optional"
Usage
parseIfNumber"not a number".valueOf || 0 // 0parseIfNumber"123".valueOf || 0 // 123parseIfNumber".1".valueOf || 0 // 0.1 parseIfNumber"not a number" // nilparseIfNumber"123" // 123 // All objects are optionals"string".valueOf || "default" // "string" nonOptional = 123// ^^^ number cannot be assigned to string optional = 123// ^^^ number cannot be assigned to Optional<string> nonOptional = "string" // Validoptional = "string" // Also valid nonOptional = nil// ^^^ Optional<any> cannot be assigned to stringoptional = nil // Valid
Unwrap an optional by using isNil
and valueOf()
.
if maybeNumber.isNil else
The optional is not its own object, so casting works as well as equality checks.
parseIfNumber"123" === 123 // trueparseIfNumber"not a number" === nil // trueparseIfNumber"123" === nil // false