Skip to content

Commit

Permalink
feat(schema) add StringEnum to typebox module
Browse files Browse the repository at this point in the history
  • Loading branch information
marshallswain committed Oct 21, 2022
1 parent 7d219d9 commit f5a6e9a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
31 changes: 31 additions & 0 deletions docs/api/schema/typebox.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,8 +269,39 @@ const T = {
}
```

##### StringEnum

`StringEnum` is a standalone utility to for specifying an array of allowed string values on a property. It is directly exported from `@feathersjs/typebox`:

```js
// import the module, first
import { StringEnum } from '@feathersjs/typebox'

const T = StringEnum(['crow', 'dove', 'eagle'])
```

To obtain the TypeScript type, use the `Static` utility:

```js
import { Static } from '@feathersjs/typebox'

type T = Static<typeof T>
```

```js
const T = {
enum: ['crow', 'dove', 'eagle']
}
```

##### Enum

<BlockQuote>

For string values, use [StringEnum](#stringenum).

</BlockQuote>

```js
enum Foo {
A,
Expand Down
9 changes: 9 additions & 0 deletions packages/typebox/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,15 @@ const arrayOfKeys = <T extends TObject>(type: T) => {
return Type.Unsafe<(keyof T['properties'])[]>({ type: 'array', items: { type: 'string', enum: keys } })
}

/**
* A TypeBox utility that converts an array of provided strings into a string enum.
* @param allowedValues array of strings for the enum
* @returns TypeBox.Type
*/
export function StringEnum<T extends string[]>(allowedValues: [...T]) {
return Type.Unsafe<T[number]>({ type: 'string', enum: allowedValues })
}

export function sortDefinition<T extends TObject>(schema: T) {
const properties = Object.keys(schema.properties).reduce((res, key) => {
const result = res as any
Expand Down

0 comments on commit f5a6e9a

Please # to comment.