Skip to content

Commit

Permalink
Add TypeScript info to Docs (#393)
Browse files Browse the repository at this point in the history
  • Loading branch information
thesunny authored Jun 20, 2020
1 parent 4cdb8ad commit 57230d3
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions docs/guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
- [Composing Structs](#composing-structs)
- [Refining Types](#refining-types)
- [Coercing Values](#coercing-values)
- [Using TypeScript](#using-typescript)

## Installing Superstruct

Expand Down Expand Up @@ -380,3 +381,37 @@ const data = ' a wEird str1ng '
const output = coerce(data, TrimmedString)
// "a wEird str1ng"
```

## Using TypeScript

Most of the time, TypeScript "just works" but knowing a little more will help you get the most out of TypeScript.

## Custom Data Types

When you define a custom type, it is returned as `unknown` by default. In order to get better typing, you can use a generic to specify the type.

The following defines a custom email type and adds a generic to declare the value is of type `string`.

```ts
import { struct } from 'superstruct'
import isEmail from 'is-email'

const Email = struct<string>('Email', (value) => isEmail(value))
```

## Extracting a Type

If you have a struct definition, you can extract its type using the `StructType` utility.

```ts
const User = object({
id: number(),
name: string(),
})

type User = StructType<typeof User>
// type User = {
// id: number
// name: string
// }
```

0 comments on commit 57230d3

Please sign in to comment.