I hope TS adds native Swift-style optional values and chaining, where it fails at compile time if you try to access an optional without unwrapping it first. Conversely non-optional values cannot be null!
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.
I use type sugar in my projects. This helps communicate what might be null/undefined. I haven't been satisfied with something like ts-optional since it wraps the object in a function (or class, or prototype?), making it harder to serialize to JSON.
/** 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;
}
}
Have you looked at TypeScript's non-null types[0]? It gives you compile-time checks for values that might be null. I personally love it and use it for all my projects.
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.