Created
September 16, 2021 13:21
-
-
Save ryangjchandler/7363b254b8866f8310413308599d01d6 to your computer and use it in GitHub Desktop.
Typescript Optional<T> type (Rust-esque)
This file contains hidden or 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
type Option<T> = Some<T> | None<T>; | |
interface Optional<T> { | |
unwrap(): T; | |
unwrapOr(or: T): T; | |
isSome(): boolean; | |
isNone(): boolean; | |
} | |
class Some<T> implements Optional<T> { | |
constructor(private value: T) {} | |
unwrap(): T { | |
return this.value | |
} | |
unwrapOr(or: T): T { | |
return this.unwrap(); | |
} | |
isSome(): boolean { | |
return true | |
} | |
isNone(): boolean { | |
return false | |
} | |
} | |
class None<T> implements Optional<T> { | |
unwrap(): never { | |
throw new ReferenceError('Attempt to call `unwrap()` on `None` value.') | |
} | |
unwrapOr(or: T): T { | |
return or | |
} | |
isSome(): boolean { | |
return false; | |
} | |
isNone(): boolean { | |
return true; | |
} | |
} | |
function expectsOptional(value: Option<string>) { | |
if (value.isSome()) { | |
console.log(`Some: ${value.unwrap()}`) | |
} else { | |
console.log(`None`) | |
} | |
} | |
expectsOptional(new Some("Hello!")) | |
expectsOptional(new None) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment