Convert Figma logo to code with AI

gcanti logofp-ts

Functional programming in TypeScript

10,793
501
10,793
190

Top Related Projects

23,799

:ram: Practical functional Javascript

:see_no_evil: Refuge from unsafe JavaScript

Specification for interoperability of common algebraic structures in JavaScript

59,746

A modern JavaScript utility library delivering modularity, performance, & extras.

[not actively maintained!] A standard library for functional programming in JavaScript

monet.js - Monadic types library for JavaScript

Quick Overview

fp-ts is a popular TypeScript library that enables functional programming techniques in TypeScript. It provides a comprehensive set of tools and data types for writing type-safe, composable, and maintainable code using functional programming paradigms.

Pros

  • Strong type safety and inference
  • Comprehensive set of functional programming utilities and data types
  • Excellent documentation and community support
  • Seamless integration with TypeScript projects

Cons

  • Steep learning curve for developers new to functional programming
  • Can lead to increased verbosity in some cases
  • May introduce additional complexity for simple tasks
  • Performance overhead in certain scenarios due to abstraction layers

Code Examples

Example 1: Using the Option type for null-safe operations

import { Option, some, none, pipe } from 'fp-ts/Option'

const divide = (a: number, b: number): Option<number> =>
  b === 0 ? none : some(a / b)

const result = pipe(
  divide(10, 2),
  Option.map(x => x * 2),
  Option.getOrElse(() => 0)
)

console.log(result) // Output: 10

Example 2: Using the Either type for error handling

import { Either, right, left } from 'fp-ts/Either'
import { pipe } from 'fp-ts/function'

const safeParse = (s: string): Either<Error, number> => {
  const n = parseFloat(s)
  return isNaN(n) ? left(new Error(`Invalid number: ${s}`)) : right(n)
}

const result = pipe(
  safeParse('42'),
  Either.map(n => n * 2),
  Either.getOrElse(error => {
    console.error(error)
    return 0
  })
)

console.log(result) // Output: 84

Example 3: Using the Task type for asynchronous operations

import { Task } from 'fp-ts/Task'
import { pipe } from 'fp-ts/function'

const delay = (ms: number): Task<void> => () =>
  new Promise(resolve => setTimeout(resolve, ms))

const greet = (name: string): Task<string> => () =>
  Promise.resolve(`Hello, ${name}!`)

const program = pipe(
  delay(1000),
  Task.chain(() => greet('Alice')),
  Task.map(message => message.toUpperCase())
)

program().then(console.log) // Output after 1 second: HELLO, ALICE!

Getting Started

To start using fp-ts in your TypeScript project:

  1. Install the library:

    npm install fp-ts
    
  2. Import the required modules in your TypeScript file:

    import { pipe } from 'fp-ts/function'
    import * as O from 'fp-ts/Option'
    import * as E from 'fp-ts/Either'
    import * as T from 'fp-ts/Task'
    
  3. Start using fp-ts functions and data types in your code:

    const result = pipe(
      O.some(5),
      O.map(n => n * 2),
      O.getOrElse(() => 0)
    )
    console.log(result) // Output: 10
    

Competitor Comparisons

23,799

:ram: Practical functional Javascript

Pros of Ramda

  • More established and widely adopted in the JavaScript community
  • Extensive documentation and examples available
  • Simpler learning curve for developers familiar with JavaScript

Cons of Ramda

  • Less type safety compared to fp-ts
  • Limited support for advanced functional programming concepts
  • May require more boilerplate code for complex operations

Code Comparison

Ramda:

const result = R.pipe(
  R.filter(R.propEq('active', true)),
  R.map(R.prop('name')),
  R.sort(R.ascend(R.identity))
)(users);

fp-ts:

import * as A from 'fp-ts/Array'
import * as O from 'fp-ts/Option'
import { pipe } from 'fp-ts/function'

const result = pipe(
  users,
  A.filter((u) => u.active),
  A.map((u) => u.name),
  A.sort(O.getOrd(S.Ord))
)

Both libraries provide functional programming utilities, but fp-ts offers stronger type safety and more advanced FP concepts. Ramda is more accessible for JavaScript developers, while fp-ts caters to those seeking a more rigorous functional approach with TypeScript integration. The code comparison demonstrates how both libraries handle common operations like filtering, mapping, and sorting, with fp-ts showcasing its type-safe approach and Ramda its more JavaScript-like syntax.

:see_no_evil: Refuge from unsafe JavaScript

Pros of Sanctuary

  • More beginner-friendly with extensive documentation and examples
  • Stricter runtime type checking for enhanced safety
  • Smaller API surface, potentially easier to learn and use

Cons of Sanctuary

  • Less frequently updated compared to fp-ts
  • Smaller ecosystem and community support
  • May have performance overhead due to runtime type checking

Code Comparison

Sanctuary:

S.map(S.add(1), [1, 2, 3])

fp-ts:

import { array } from 'fp-ts'
import { pipe } from 'fp-ts/function'

pipe([1, 2, 3], array.map(n => n + 1))

Key Differences

  • Sanctuary focuses on runtime type checking, while fp-ts leverages TypeScript's static typing
  • fp-ts has a larger API surface with more advanced functional programming concepts
  • Sanctuary aims for simplicity and safety, while fp-ts prioritizes performance and flexibility

Use Cases

  • Choose Sanctuary for projects prioritizing runtime safety and simplicity
  • Opt for fp-ts in TypeScript projects requiring advanced FP concepts and performance

Both libraries provide functional programming tools for JavaScript, but they cater to different preferences and requirements. The choice between them depends on project needs, team expertise, and desired balance between safety and performance.

Specification for interoperability of common algebraic structures in JavaScript

Pros of fantasy-land

  • Provides a specification for algebraic structures in JavaScript
  • Language-agnostic, allowing implementations in various JS flavors
  • Widely adopted standard in the functional programming community

Cons of fantasy-land

  • Primarily a specification, not a full implementation
  • Requires additional libraries or custom code for practical use
  • May have a steeper learning curve for developers new to algebraic structures

Code Comparison

fantasy-land (specification):

const Functor = {
  map: (f) => (fa) => /* ... */
};

fp-ts (implementation):

const array = {
  map: <A, B>(f: (a: A) => B) => (fa: Array<A>): Array<B> =>
    fa.map(f)
};

Key Differences

  • fp-ts provides a comprehensive implementation of functional programming concepts
  • fantasy-land focuses on standardizing interfaces for algebraic structures
  • fp-ts is TypeScript-centric, while fantasy-land is language-agnostic
  • fp-ts offers more out-of-the-box functionality and utilities
  • fantasy-land allows for more flexibility in implementation across different libraries

Both projects contribute significantly to functional programming in JavaScript, with fp-ts offering a more complete toolkit and fantasy-land providing a common specification for interoperability between libraries.

59,746

A modern JavaScript utility library delivering modularity, performance, & extras.

Pros of Lodash

  • Widely adopted and well-established utility library
  • Extensive collection of functions for common programming tasks
  • Easier learning curve for developers familiar with imperative programming

Cons of Lodash

  • Less emphasis on functional programming concepts
  • Limited support for advanced type safety and inference
  • May encourage a more imperative coding style

Code Comparison

fp-ts example:

import { pipe } from 'fp-ts/function'
import { map, filter } from 'fp-ts/Array'

const result = pipe(
  [1, 2, 3, 4, 5],
  filter(n => n % 2 === 0),
  map(n => n * 2)
)

Lodash example:

import _ from 'lodash'

const result = _.chain([1, 2, 3, 4, 5])
  .filter(n => n % 2 === 0)
  .map(n => n * 2)
  .value()

Summary

fp-ts focuses on functional programming principles and leverages TypeScript's type system for enhanced safety. It provides a more rigorous approach to functional programming but may have a steeper learning curve.

Lodash offers a broader set of utility functions and is more accessible to developers with various programming backgrounds. However, it may not provide the same level of type safety and functional programming support as fp-ts.

The choice between the two libraries depends on the project requirements, team expertise, and desired programming paradigm.

[not actively maintained!] A standard library for functional programming in JavaScript

Pros of Folktale

  • Simpler API and easier learning curve for beginners
  • More idiomatic JavaScript approach
  • Better documentation with clear examples and use cases

Cons of Folktale

  • Smaller ecosystem and community compared to fp-ts
  • Less comprehensive in terms of functional programming constructs
  • Not as actively maintained as fp-ts

Code Comparison

Folktale:

const { Result } = require('folktale');

const divide = (a, b) =>
  b === 0 ? Result.Error('Division by zero') : Result.Ok(a / b);

divide(10, 2).map(x => x * 2).getOrElse(0);

fp-ts:

import { pipe } from 'fp-ts/function';
import * as E from 'fp-ts/Either';

const divide = (a: number, b: number): E.Either<string, number> =>
  b === 0 ? E.left('Division by zero') : E.right(a / b);

pipe(divide(10, 2), E.map(x => x * 2), E.getOrElse(() => 0));

Both libraries provide similar functionality for handling computations that may fail, but fp-ts offers a more type-safe approach with its TypeScript integration. Folktale's API is more straightforward, while fp-ts provides a more comprehensive set of functional programming tools.

monet.js - Monadic types library for JavaScript

Pros of monet.js

  • Simpler API with fewer concepts to learn
  • More beginner-friendly documentation
  • Smaller bundle size, potentially better for lightweight applications

Cons of monet.js

  • Less comprehensive type system compared to fp-ts
  • Fewer advanced functional programming features
  • Less active development and community support

Code Comparison

monet.js:

const result = Maybe.fromNull(someValue)
  .map(x => x * 2)
  .orElse('default');

fp-ts:

import { pipe } from 'fp-ts/function'
import * as O from 'fp-ts/Option'

const result = pipe(
  O.fromNullable(someValue),
  O.map(x => x * 2),
  O.getOrElse(() => 'default')
)

Both libraries provide similar functionality for handling optional values, but fp-ts offers more type safety and composability at the cost of increased verbosity. monet.js has a more concise syntax, which may be preferable for simpler use cases or developers new to functional programming. However, fp-ts provides a more robust ecosystem and better integration with TypeScript, making it a stronger choice for larger, more complex projects.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Functional programming in TypeScript

build status npm downloads

📢 Important Announcement: fp-ts is Joining the Effect-TS Ecosystem!

We are excited to announce that the fp-ts project is officially merging with the Effect-TS ecosystem. This is a significant step forward in the functional programming landscape, bringing together two powerful libraries under one roof. Giulio Canti, the author of fp-ts, is being welcomed into the Effect organization, promising an exciting future with enhanced capabilities and support.

What This Means for New Users:

Effect-TS can be regarded as the successor to fp-ts v2 and embodies what would be considered fp-ts v3. This merger marks a significant evolution in the library's capabilities, integrating more features and functionalities tailored towards robust, type-safe, and scalable functional programming.

For more details on this merger and what it entails, please refer to the official announcement here. Additionally, you can explore more about Effect-TS and its offerings on our website and documentation.

Introduction

fp-ts is a library for typed functional programming in TypeScript.

fp-ts aims to allow developers to use popular patterns and abstractions that are available in most functional languages. For this, it includes the most popular data types, type classes and abstractions such as Option, Either, IO, Task, Functor, Applicative, Monad to empower users to write pure FP apps and libraries built atop higher order abstractions.

A distinctive feature of fp-ts with respect to other functional libraries is its implementation of Higher Kinded Types, which TypeScript doesn't support natively.

Inspired by

Sponsors

Unsplash
Unsplash
https://unsplash.com/

The internet’s source for visuals.
Powered by creators everywhere.

Installation

To install the stable version:

npm install fp-ts

Make sure to always have a single version of fp-ts installed in your project. Multiple versions are known to cause tsc to hang during compilation. You can check the versions currently installed using npm ls fp-ts (make sure there's a single version and all the others are marked as deduped).

TypeScript compatibility

Strictness – This library is conceived, tested and is supposed to be consumed by TypeScript with the strict flag turned on.

fp-ts versionrequired typescript version
2.0.x+3.5+
1.15.x+3.1+
<= 1.14.42.8+ (*)

(*) If you are running < typescript@3.0.1 you have to polyfill the unknown type. You can use unknown-ts as a polyfill.

Documentation

Disclaimer. Teaching functional programming is out of scope of this project, so the documentation assumes you already know what FP is.

Help

If you need help with fp-ts check out:

Development

License

The MIT License (MIT)

NPM DownloadsLast 30 Days