From a1553ac0bfef8bc137934ac604ac880834e4ed08 Mon Sep 17 00:00:00 2001 From: baldo Date: Thu, 25 Aug 2022 21:10:37 +0200 Subject: [PATCH] Replace EnumValue type by more general TypeOf type. --- server/shared/types/index.ts | 15 +++++---------- server/utils/resources.ts | 8 ++++---- 2 files changed, 9 insertions(+), 14 deletions(-) diff --git a/server/shared/types/index.ts b/server/shared/types/index.ts index 5c8a77e..b4677d8 100644 --- a/server/shared/types/index.ts +++ b/server/shared/types/index.ts @@ -1,9 +1,4 @@ -import { - ArrayField, - Field, - RawJsonField, - registerStringMapper, -} from "sparkson"; +import { ArrayField, Field, RawJsonField } from "sparkson"; // Types shared with the client. export type TypeGuard = (arg: unknown) => arg is T; @@ -71,8 +66,8 @@ export type JSONArray = Array; export const isJSONArray = toIsArray(isJSONValue); -export type EnumValue = E[keyof E]; -export type EnumTypeGuard = TypeGuard>; +export type ValueOf = T[keyof T]; +export type EnumTypeGuard = TypeGuard>; export function unhandledEnumField(field: never): never { throw new Error(`Unhandled enum field: ${field}`); @@ -138,7 +133,7 @@ export function isBoolean(arg: unknown): arg is boolean { } export function isUndefined(arg: unknown): arg is undefined { - return arg === undefined; + return typeof arg === "undefined"; } export function isNull(arg: unknown): arg is null { @@ -150,7 +145,7 @@ export function toIsArray(isT: TypeGuard): TypeGuard { } export function toIsEnum(enumDef: E): EnumTypeGuard { - return (arg): arg is EnumValue => + return (arg): arg is ValueOf => Object.values(enumDef).includes(arg as [keyof E]); } diff --git a/server/utils/resources.ts b/server/utils/resources.ts index 218c939..e218f1a 100644 --- a/server/utils/resources.ts +++ b/server/utils/resources.ts @@ -12,7 +12,7 @@ import { import { Request, Response } from "express"; import { EnumTypeGuard, - EnumValue, + ValueOf, type GenericSortField, getFieldIfExists, isJSONObject, @@ -79,10 +79,10 @@ function respond( function orderByClause( restParams: RestParams, - defaultSortField: EnumValue, + defaultSortField: ValueOf, isSortField: EnumTypeGuard ): OrderByClause { - let sortField: EnumValue | undefined = isSortField(restParams._sortField) + let sortField: ValueOf | undefined = isSortField(restParams._sortField) ? restParams._sortField : undefined; if (!sortField) { @@ -347,7 +347,7 @@ export { filterCondition as whereCondition }; export function filterClause( restParams: RestParams, - defaultSortField: EnumValue, + defaultSortField: ValueOf, isSortField: EnumTypeGuard, filterFields: string[] ): FilterClause {