As I embark on my journey with the fp-ts
library, a question arises in my mind: What benefits does the Option type offer compared to TypeScript's standard method of handling optional values using the question mark ?
operator?
As I embark on my journey with the fp-ts
library, a question arises in my mind: What benefits does the Option type offer compared to TypeScript's standard method of handling optional values using the question mark ?
operator?
When working with Typescript, using the question mark can indicate whether a value exists or not. However, leveraging the Option type from fp-ts becomes essential when performing computations on these values.
For instance, consider a scenario where we have two items in a shop, each with optional prices, and we need to retrieve both prices or return a default value indicating "not for sale". Let's first examine how this would be approached in standard Typescript:
type ShopItem = {
price?: number
}
const getPrice = (item1: ShopItem, item2: ShopItem): number | null => {
const price1 = item1.price;
const price2 = item2.price;
if (price1 && price2) {
return price1 + price2;
}
return null;
}
However, this approach has its drawbacks. It may overlook cases where the price is 0, mistakenly labeling the item as unavailable. Additionally, it lacks scalability when dealing with multiple ShopItems or other item types with optional values, requiring repetitive checks for null values.
Now, let's compare this to the alternative presented by fp-ts: https://codesandbox.io/s/laughing-wu-pffe3
import { some, none, ap, Option } from "fp-ts/lib/Option";
import { pipe } from 'fp-ts/lib/pipeable'
type ShopItem = {
price: Option<number> //either Some<number> or None
}
const getPrice = (item1: ShopItem, item2: ShopItem): Option<number> =>
pipe(
some((a: number) => (b: number) => a + b),
ap(item1.price),
ap(item2.price)
);
This functional approach simplifies the process by abstracting away null checks into the None type. By utilizing fp-ts, the addition function is directly applied to the item prices without explicit conditional statements.
While I understand @derp's points, I must admit that his code snippet may not be the most optimal. The pipe()
API can be quite confusing to grasp, and on top of that, it seems that fp-ts is considered a deprecated library.
Further details include:
For additional insights, check out Would an Option or Optional type (Option<T>) make sense in TypeScript?
Here is an example array: subjectWithTopics = [ {subjectName:"maths", topicName : "topic1 of maths " }, {subjectName:"maths", topicName : "topic2 of maths " }, {subjectName:"English", topicName : &quo ...
https://i.stack.imgur.com/htnkb.png type Test = number[][]; // The Test type will be inferred as 'number' based on the image above. Can you explain why number[] is considered an index signature type with a signature of 'number'? ...
I've been struggling for a few days now trying to adjust the UTC time in an area chart using Angular2-HighCharts. The backend API is returning timestamps which I then inject into the chart, but each time it's being converted to "human time" with ...
While exploring the Vue.js source code located at packages/reactivity/src/effects.ts, I came across this snippet: export interface ReactiveEffectRunner<T = any> { (): T effect: ReactiveEffect } I'm curious, what does () signify in the code ...
I seem to be struggling with understanding how TSyringe handles classes with dependencies. To illustrate my issue, I have created a simple example. In my index.tsx file, following the documentation, I import reflect-metadata. When injecting a singleton cl ...
Searching for an elegant solution (without resorting to private APIs) to create a widget-style dashboard. The goal is to dynamically load components based on user role. Is there a way to import a component and its dependencies included in the component&ap ...
Currently, I am utilizing Angular v16 alongside Angular Fire v16 and Firebase v9. Following the instructions, I completed all the necessary setup steps including executing firebase login, firebase init, and converting the functions to typescript. Next, wi ...
I've integrated the Firebase Admin SDK for handling administrative tasks. The functions I've set up are hosted on Firebase Cloud Function in my console. While I can successfully trigger these functions from my application, I'm facing an issu ...
I'm currently working on a component that can render either a router Link or a Button based on the provided props. Here is the code snippet I have: import React from 'react'; import Button from '@material-ui/core/Button'; import { ...
I'm struggling with programming a calculator for my class. I followed the instructions from our lesson, but it's not functioning properly and I can't pinpoint the issue. I just need a hint on where the problem might be located. The calculat ...
I encountered an error message with code TS7053 which states: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; isLandlocked: boolean; }'. No index signa ...
Let's discuss a scenario with a reference: someReference; The someReference is essentially a React component structured like this: class SomeComponent<IProps> { getData = () => {}; render() { ...some content } } Now, how c ...
Take a look at the following pseudo-code attempting to define a higher-order type function with a function-typed parameter M<?>: type HigherOrderTypeFn<T, M<?>> = T extends (...) ? M<T> : never; The syntax M<?> is not va ...
Knex version: 2.5.1 Database + version: postgres15 When passing a union typescript definition into knex as a type annotation, it returns the type any. However, by using type assertion as UserRecord, we can obtain the correct UserRecord type. It is my un ...
Whenever I attempt to compile the project for production, an error pops up: There is a problem resolving all parameters for EmployeeComponent in C:/.../src/app/employee/employee.component.ts: (?, ?, ?). Oddly enough, when I run the application, every ...
Encountering an issue with mocha-typescript throwing an error indicating that describe is not defined. TypeError: mocha_typescript_1.describe is not a function at DatabaseTest.WrongPath (test/database_test.ts:21:9) at Context.<anonymous> ...
I am encountering an issue with the code snippet below in my application request.ts import request from 'request' export const funcA = async ( apiToken: string, body: any): Promise<any> => { return new Promise((resolve, reject) =&g ...
I have a scenario where I need to display time slots at 30-minute intervals using Mat Select. export const TIME=["12:00 AM","12:30 AM","01:00 AM","01:30 AM","02:00 AM","02:30 AM","03:00 AM&qu ...
While working on my Nest project, I encountered an issue with the Mongoose package. When attempting to build the project using npm run build, an error appeared in the console: node_modules/mongoose/node_modules/mongodb/mongodb.d.ts:34:15 - error TS2305: Mo ...
When using typescript and trying to style Material UI components with styled-components, encountering a type error with StyledComponent displaying Type '{ children: string; }' is missing the following properties import React, { PureComponent } f ...