Skip to content

Commit

Permalink
fix: better docs with new example
Browse files Browse the repository at this point in the history
  • Loading branch information
becelli committed Dec 26, 2023
1 parent 8eb42d1 commit d031d05
Showing 1 changed file with 36 additions and 3 deletions.
39 changes: 36 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,44 @@ npm install ooptional
import { Optional, Option } from "ooptional";
```

## Practical example: validating a user

```ts
import { Optional, Option } from "ooptional";

export class UserService {
// no optional type 😥
public verifyCanCreateAccount(user: User): boolean {
if (user.age < 18) {
return false;
}

if (!user.email) {
return false;
}

if (!user.password) {
return false;
}

return true;
}

// with optional type 😋
public verifyCanCreateAccount(user: User): boolean {
return Option.of(user)
.filter((user) => user.age >= 18)
.filter((user) => user.email)
.filter((user) => user.password)
.isSome();
}
}
```

### Creating an Optional

```ts
const optional: Optional<string> = Option.ofNullable("Hello, world!");
const optional: Optional<string> = Option.of("Hello, world!");

// or
const some: Some<string> = Option.some("Hello, world!");
Expand All @@ -35,7 +69,7 @@ const noneAsOptional: Optional<string> = Option.none();
### Checking if an Optional has a value

```ts
const optional: Optional<string> = Option.ofNullable("Hello, world!");
const optional: Optional<string> = Option.of("Hello, world!");

if (optional.isSome()) {
console.log(
Expand Down Expand Up @@ -74,7 +108,6 @@ The `Option` class has the following methods:
- `toNullable(): T | null`: Returns the value if it exists, otherwise returns null.
- `toUndefined(): T | undefined`: Returns the value if it exists, otherwise returns undefined.


### Some class

The `Some` class is one of the variants of `Option`. It represents a value that exists. It has similar methods to `None`, but they behave differently as they have a value to work with.
Expand Down

0 comments on commit d031d05

Please sign in to comment.