Support
Quality
Security
License
Reuse
kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
Get all kandi verified functions for this library.
Functional programming in TypeScript
QUESTION
fp-ts Option, Typescript and undefined
Asked 2022-Mar-17 at 14:49I'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>
ANSWER
Answered 2021-Sep-13 at 18:43The 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>>
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
See Similar Libraries in
Save this library and start creating your kit
Open Weaver – Develop Applications Faster with Open Source