Last active
February 17, 2016 06:26
-
-
Save emilniklas/50233d1b6025f0fc60dc to your computer and use it in GitHub Desktop.
Implementation of optional types in TypeScript. Just replace `null` with `nil` in your app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
declare interface Optional<T> { | |
isNil: boolean | |
valueOf(): T | |
} | |
declare const nil: Optional<any> | |
interface Object { | |
isNil: boolean | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var nil = { isNil: true, valueOf: function() { return undefined } }; | |
Object.prototype.isNil = false; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <reference path="./optional.d.ts" /> | |
// Passing in an Optional | |
// ====================== | |
function expectsAnOptional(optional: Optional<number>) { | |
if (optional.isNil) { | |
// Nil was provided | |
} else { | |
const value = optional.valueOf() // Unwrap | |
} | |
} | |
function expectsNonOptional(concrete: number) {} | |
// expectsAnOptional("string") <-- Error, expects number | |
expectsAnOptional(nil) // <-- Works, is optional | |
expectsAnOptional(123) // <-- Works | |
// expectsNonOptional("string") <-- Error, expects number | |
// expectsNonOptional(nil) <-- Error, doesn't allow optional | |
expectsNonOptional(123) // <-- Works | |
// Returning an Optional | |
// ===================== | |
function returnsAnOptional(): Optional<number> { | |
if (someCondition) { | |
return nil // <-- Works, returns optional | |
} else { | |
// return "string" <-- Error, can't return string | |
return 123 // <-- Works, returns number | |
} | |
} | |
function returnsNonOptional(): number { | |
if (someCondition) { | |
// return nil <-- Error, can't return optional | |
} else { | |
// return "string" <-- Error, can't return string | |
return 123 // <-- Works, returns number | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment