Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

feat(schema) add StringEnum to typebox module #2827

Merged
merged 2 commits into from
Nov 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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