What is the typescript equivalent for ReasonML's option type?

437 views Asked by At

In ReasonML option type is a variant which can either be Some('a) or None.

How would I model the same thing in typescript?

2

There are 2 answers

0
T.J. Crowder On BEST ANSWER

TypeScript doesn't have a direct equivalent. What you'd do instead depends a bit on what you're using it for: A property, a function parameter, a variable or function return type...

If you're using it for a property (in an object/interface), you'd probably use optional properties, for instance:

interface Something {
   myProperty?: SomeType;
//           ^−−−−− marks it as optional
}

The same notation works for function parameters.

For variables or return types, you might use a union type with undefined or null, e.g.:

let example: SomeType | undefined;
// or
let example: SomeType | null = null;

The first one says that example can be of type SomeType or undefined, the second say it can be SomeType or null. (Note the latter needed an initializer, since otherwise example would be undefined, and that isn't a valid value for SomeType | null.)

3
Yesset Zhussupov On

Perhaps, something like this:

export type None = never;

export type Some<A> = A;

export type Option<A> = None | Some<A>

If you're interested in functional programming with ts, you could take a look at fp-ts