Search code examples
reactjstypescriptundefinedoption-typefp-ts

fp-ts Option, Typescript and undefined


I'm trying to create a simple helper function using fp-ts/Option and Typescript that takes a an arbitrary value and returns it as an Option<T>.

export const toOption = <T>(val: T): Option<T> => {
  return fromNullable(val);
};

The problem I'm having is, that no matter what I do, it includes undefined in the option. In somefile.tsx I have an object whose key value uses the toOption function. I need for that value to be an Option only but instead it reads the type as (property) airDate: Option<(string & Date) | undefined>

{
airDate:toOption(attributes.airDate), // (property) airDate: Option<(string & Date) | undefined>
}

Using type-guards

export const toOption = <T>(val: T): Option<T> => {
  if(typeof val == undefined) return none;
  return fromNullable(val);
};

Ternary

export const toOption = <T>(val: T): Option<T> => {
  return val ? some(val) : none;
};

Conditional

export const toOption = <T>(val: T): Option<T> => {
  if(!val) return none;
  return some(val)
};

They all yield the same type in the end: (property) airDate: Option<(string & Date) | undefined>


Solution

  • The typescript utility type NonNullable comes in handy at times like this.

    export const toOption = <T>(val: T): Option<NonNullable<T>> => {
      return fromNullable(val);
    };
    

    But notice that there are no different between toOption and fromNullable, so if you want to use the name toOption, you could just assign the function as a value to toOption variable/const

    export const toOption = fromNullable
    

    You don't need to annotate the type because fromNullable's signature already is <A>(a: A) => Option<NonNullable<A>>