Search code examples
typescriptreasonrescript

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


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

How would I model the same thing in typescript?


Solution

  • 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.)