Skip to content

Instantly share code, notes, and snippets.

@JavadocMD
Created July 22, 2019 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JavadocMD/8929779b3fad16d38ef3552ce2cc311b to your computer and use it in GitHub Desktop.
Save JavadocMD/8929779b3fad16d38ef3552ce2cc311b to your computer and use it in GitHub Desktop.
A simple example demonstrating the use of never in TypeScript.
// Let's assume we're writing our own Option type (in practice, you should probably use fp-ts or something).
export abstract class Option<T> {
public abstract map<U>(f: (t: T) => U): Option<U>
}
// Some needs a type parameter so we know what value it has.
export class Some<T> extends Option<T> {
constructor(public readonly value: T) {
super()
}
public map<U>(f: (t: T) => U): Some<U> {
return new Some(f(this.value))
}
}
// But None never has a value! We can use `never` everywhere we used `T`.
class None extends Option<never> {
constructor() {
super()
}
public map<U>(f: (t: never) => U): None {
return this
}
}
// And therefore a singleton instance of None is all we need!
// Otherwise we'd have to construct a new None for every `T` we ran across, which would be silly.
export const none = new None()
// e.g.
new Some(1).map(x => x + 2) // Some(3)
none.map(x => x + 2) // None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment