Option Type For Null Safety
Implement an Option type for null safety with map and match for explicit absence handling without null checks.
Code
export type Option<T>={tag:'some';value:T}|{tag:'none'};export function some<T>(value:T):Option<T>{return{tag:'some',value};}export function none<T>():Option<T>{return{tag:'none'};}export function isSome<T>(o:Option<T>):o is{tag:'some';value:T}{return o.tag==='some';}export function map<T,U>(o:Option<T>,fn:(v:T)=>U):Option<U>{return o.tag==='some'?some(fn(o.value)):none();}export function flatMap<T,U>(o:Option<T>,fn:(v:T)=>Option<U>):Option<U>{return o.tag==='some'?fn(o.value):none();}export function match<T,U>(o:Option<T>,onSome:(v:T)=>U,onNone:()=>U):U{return o.tag==='some'?onSome(o.value):onNone();}export function fromNullable<T>(v:T|null|undefined):Option<T>{return v==null?none():some(v);}What to watch for
Absence is a tagged value here, not null: Option<T> is a discriminated union of { tag: 'some'; value: T } and { tag: 'none' }, with some and none as the only constructors, so a T always travels inside a some.
The guard isSome narrows with a type predicate — o is { tag: 'some'; value: T } — so after a true check, o.value is readable without a cast. map dispatches on the tag: o.tag === 'some' ? some(fn(o.value)) : none(), and stays an Option<U> rather than leaking the inner value. flatMap differs only in that fn already returns an Option<U>, which is what prevents Option<Option<T>> from forming.
match forces the caller to supply both branches — onSome for the value and onNone for absence — so forgetting a case is a compile error, not a runtime surprise. fromNullable is the bridge from ordinary code: v == null ? none() : some(v) converts a possibly-null input at the boundary.
Interactive Tools for This Topic
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language.
Report a problem with this exampleOpens a pre-filled issue on GitHub.