by snugbug · 9y ago · 0 comments
There are projects that add optional functionality (https://www.npmjs.com/package/ts-optional), but I don't see how it prevents you from setting regular values to null.
/** Represents optional values, just as F# does. */
export type Option<T> = T | null | undefined;
/** Option operators. */
export namespace Option {
/** Constructs a Some(value) option. */
export function some<T>(value: T): Option<T> {
return value;
}
/** Returns true if the value is Some value and false otherwise. */
export function isSome<T>(value: Option<T>): value is T {
return value !== undefined && value !== null;
}
/** Constructs a None option. */
export function none<T>(): Option<T> {
return null;
}
/** Returns true if the value is null or undefined and false otherwise. */
export function isNone<T>(value: Option<T>): value is null | undefined {
return value === undefined || value === null;
}
/** Recovers an Option<T> from JSON object representation. */
export function fromJSON<T>(json: any): Option<T> {
return isSome(json) ? <T>(json[0]) : null;
}
/** Converts to a JSON representation. */
export function toJSON<T>(value: Option<T>): any {
return isSome(value) ? [value] : null;
}
/** Unpacks with a default value. */
export function withDefault<T>(value: Option<T>, defaultValue: T): T {
return isSome(value) ? value : defaultValue;
}
}
EDIT: Forgot to mention, I got this from Gluon. https://github.com/Tachyus/gluon/blob/master/src/Gluon.Clien...[0]: https://blog.mariusschulz.com/2016/09/27/typescript-2-0-non-...