In ReasonML option
type is a variant which can either be Some('a)
or None
.
How would I model the same thing in typescript?
In ReasonML option
type is a variant which can either be Some('a)
or None
.
How would I model the same thing in typescript?
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
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:
The same notation works for function parameters.
For variables or return types, you might use a union type with
undefined
ornull
, e.g.:The first one says that
example
can be of typeSomeType
orundefined
, the second say it can beSomeType
ornull
. (Note the latter needed an initializer, since otherwiseexample
would beundefined
, and that isn't a valid value forSomeType | null
.)