From f5a6e9ad8945cb1cf4298779add0154259164e6f Mon Sep 17 00:00:00 2001 From: Marshall Thompson Date: Fri, 21 Oct 2022 11:23:48 -0600 Subject: [PATCH] feat(schema) add StringEnum to typebox module --- docs/api/schema/typebox.md | 31 +++++++++++++++++++++++++++++++ packages/typebox/src/index.ts | 9 +++++++++ 2 files changed, 40 insertions(+) diff --git a/docs/api/schema/typebox.md b/docs/api/schema/typebox.md index 1e36c13a73..9a4819aec8 100644 --- a/docs/api/schema/typebox.md +++ b/docs/api/schema/typebox.md @@ -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 +``` + +```js +const T = { + enum: ['crow', 'dove', 'eagle'] +} +``` + ##### Enum +
+ +For string values, use [StringEnum](#stringenum). + +
+ ```js enum Foo { A, diff --git a/packages/typebox/src/index.ts b/packages/typebox/src/index.ts index 350cb29d4d..aaf9d47943 100644 --- a/packages/typebox/src/index.ts +++ b/packages/typebox/src/index.ts @@ -38,6 +38,15 @@ const arrayOfKeys = (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(allowedValues: [...T]) { + return Type.Unsafe({ type: 'string', enum: allowedValues }) +} + export function sortDefinition(schema: T) { const properties = Object.keys(schema.properties).reduce((res, key) => { const result = res as any