@guildxyz/types
Version:
Types related to the Guild.xyz API
59 lines (47 loc) • 1.72 kB
text/typescript
/* eslint-disable import/prefer-default-export */
import { ErrorMessages } from "./consts";
const ZERO_CODE = 48;
const NINE_CODE = ZERO_CODE + 9;
const isCharNumeric = (char: string) =>
char.charCodeAt(0) >= ZERO_CODE && char.charCodeAt(0) <= NINE_CODE;
export const isNumeric = (str: string) =>
[...str].every((char) => isCharNumeric(char));
export const nonEmptyRefine = (message = ErrorMessages.EMPTY_OBJECT) =>
[
(someObject: any) => Object.keys(someObject).length > 0,
{ message },
] as const;
// Can be used for "casting" an array literal to a mutable tuple type. Practically the same as "[...] as const", but without making the type "readonly"
export function toTupleType<T extends [any, ...any]>(v: T) {
return v;
}
export function isoDatetimeStringRefine() {
return [
(str: string) => new Date(str).toISOString() === str,
{
message: "Requirement createdAt should be a valid ISO datetime Sstring",
},
] as const;
}
export function transformToDate(dateInput: string | number | Date) {
return new Date(dateInput);
}
export type UnionToIntersection<U> = (
U extends any ? (k: U) => void : never
) extends (k: infer I) => void
? I
: never;
export type UnionToTuple<U> =
UnionToIntersection<U extends any ? (a: U) => U : never> extends (
a: infer A
) => any
? [...UnionToTuple<Exclude<U, A>>, A]
: [];
/** When dynamically creating `z.enum()`, zod needs to know that the array has at least 2 elements */
export function createZodSafeEnumValues<T>(arr: T[]) {
if (arr.length < 2)
throw new Error(
`zod enum safe array must have at least 2 elements, received ${arr.length}`
);
return [arr[0], ...arr.slice(1)] as [T, ...T[]];
}