ArkType generic utilities #758
Replies: 2 comments 1 reply
-
function enumerateStrings<T extends readonly string[]>(values: T) {
return values.map((v) => `"${v}"`).join('|') as `"${T[number]}"`
}
const sort = type(enumerateStrings(['asc', 'desc'] as const)) // `"asc" | "desc"`, which is parsed to "asc" | "desc"
function enumerateNums<T extends readonly number[]>(values: T) {
return values.map((v) => `${v}`).join('|') as `${T[number]}`
}
const nums = type(enumerateNums([1, 2, 3] as const)) // `1 | 2 | 3`, which is parsed to 1 | 2 | 3
function valuesOfRecord<T extends Record<string, number>>(input: T) {
return Object.values(input).join('|') as `${T[keyof T]}`
}
const valuesOfCrud = type(valuesOfRecord({ add: 1, remove: 2 } as const)) // `1 | 2` which is parsed to 1 | 2 String constants need to be surrounded by quotes, but numbers don't. I'm not sure of a way to represent both of those at the same time in the same string template, so both helpers can only represent either at a time: a union of numbers, a union of string constants, but not a union of numbers and string constants. |
Beta Was this translation helpful? Give feedback.
-
Highly niche utility to add a complimentary, simplified schema for each key of a type. In my use case, an API returns the full data for each field in a field named Here's what I came up with, with the help of the one and only @ssalbdivad: const addBothFields = <const T extends object>(t: T) => {
return Object.fromEntries(
Object.entries(t).flatMap(([k, v]) => [
[k, v === 'number' ? 'number' : 'string'],
[`${k.endsWith('?') ? k.slice(0, -1) : k}_raw`, v],
]),
) as {
[k in keyof T as k extends string
? k extends `${infer Field extends string}?`
? `${Field}_raw?`
: `${k}_raw`
: k]: T[k];
} & {
// html fields
[K in keyof T]: T[K] extends 'number' ? 'number' : 'string';
};
};
export const schema = type(
addBothFields({
field_1: "'Pending'|'Paid'|string",
'field_2?': type({ id: 'string', identifier: 'string' }).or('null'),
field_3: 'number',
field_4: 'Date',
}),
);
// outputs:
export const fullSchema = type({
field_1: "'Pending'|'Paid'|string",
field_1_raw: 'string',
'field_2?': type({ id: 'string', identifier: 'string' }).or('null'),
'field_2_raw?': 'string',
field_3: 'number',
field_3_raw: 'number',
field_4: 'Date',
field_4_raw: 'string',
);
|
Beta Was this translation helpful? Give feedback.
-
In addition to the native generic syntax (#425) we plan to add in the coming weeks, ArkType can combine powerfully with TypeScript generics to create new validators or other utilities.
A simple example would be:
If while using ArkType, you've created a utility that may be useful for others in the community, post it here with a 1-sentence summary of how it's used.
Eventually, maybe we can create a community-maintained utility package. Some might eventually find their way into the core package itself! ⛵
Beta Was this translation helpful? Give feedback.
All reactions