Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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) {
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() {
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) => x + 2) // None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment