Hacker Newsnew | past | comments | ask | show | jobs | submit | snugbug's commentslogin

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;
        }
    }
EDIT: Forgot to mention, I got this from Gluon. https://github.com/Tachyus/gluon/blob/master/src/Gluon.Clien...


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.

[0]: https://blog.mariusschulz.com/2016/09/27/typescript-2-0-non-...


Isn't this just the strictNullChecks flag?


What do you mean by "Swift-style"? TypeScript allows you to declare optional values on an object:

interface Test{

number? myOptionalNumber;

}

Is that what you mean?


It is. I guess then you have to use the --strictNullChecks compiler flag to get the rest of the benefits


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: