4 ms·
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. Con
by snugbug 9y ago
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 https://www.npmjs.com/package/ts-optional), but I don't see how it prevents you from setting regular values to null.
- zip1234 9y agoWhat 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?
- snugbug 9y agoIt is. I guess then you have to use the --strictNullChecks compiler flag to get the rest of the benefits
- RyanCavanaugh 9y agoIsn't this just the strictNullChecks flag?
- judah 9y agoHave 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-nullable-types https://blog.mariusschulz.com/2016/09/27/typescript-2-0-non-...
- pininja 9y agoI 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.Client/Gluon.ts https://github.com/Tachyus/gluon/blob/master/src/Gluon.Clien...