Skip to content

Commit

Permalink
Add functional analogue of satisfies operator (Effect-TS#2080)
Browse files Browse the repository at this point in the history
Co-authored-by: maksim.khramtsov <maksim.khramtsov@btsdigital.kz>
Co-authored-by: Michael Arnaldi <michael.arnaldi@effectful.co>
  • Loading branch information
3 people authored Feb 14, 2024
1 parent dbff62c commit 11be07b
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .changeset/mean-dancers-judge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
"effect": patch
---

Add functional analogue of `satisfies` operator.
This is a convenient operator to use in the `pipe` chain to localize type errors closer to their source.

```ts
import { satisfies } from "effect/Function"

const test1 = satisfies<number>()(5 as const)
// ^? const test: 5

// @ts-expect-error
const test2 = satisfies<string>()(5)
// ^? Argument of type 'number' is not assignable to parameter of type 'string'
```
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ build/
docs/
scratchpad/
.direnv/
.idea/
19 changes: 19 additions & 0 deletions packages/effect/src/Function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,25 @@ export interface FunctionN<A extends ReadonlyArray<unknown>, B> {
*/
export const identity = <A>(a: A): A => a

/**
* A function that ensures that the type of an expression matches some type,
* without changing the resulting type of that expression.
*
* @example
* import { satisfies } from "effect/Function"
*
* const test1 = satisfies<number>()(5 as const)
* //^? const test: 5
* // @ts-expect-error
* const test2 = satisfies<string>()(5)
* //^? Argument of type 'number' is not assignable to parameter of type 'string'
*
* assert.deepStrictEqual(satisfies<number>()(5), 5)
*
* @since 2.0.0
*/
export const satisfies = <A>() => <B extends A>(b: B) => b

/**
* Casts the result to the specified type.
*
Expand Down
6 changes: 6 additions & 0 deletions packages/effect/test/Function.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ describe("Function", () => {
deepStrictEqual(Function.unsafeCoerce, Function.identity)
})

it("satisfies", () => {
deepStrictEqual(Function.satisfies<number>()(5), 5)
// @ts-expect-error
deepStrictEqual(Function.satisfies<string>()(5), 5)
})

it("constant", () => {
deepStrictEqual(Function.constant("a")(), "a")
})
Expand Down

0 comments on commit 11be07b

Please sign in to comment.