22 lines
600 B
TypeScript
22 lines
600 B
TypeScript
import { Type } from './type.ts';
|
|
import { inspect } from 'https://deno.land/std@0.85.0/node/util.ts';
|
|
|
|
/**
|
|
* A union of literals. When you want to take an exact enum value.
|
|
*/
|
|
export function oneOf<T extends string>(literals: T[]): Type<string, T> {
|
|
const examples = literals.map(x => inspect(x)).join(', ');
|
|
return {
|
|
async from(str) {
|
|
const value = literals.find(x => x === str);
|
|
if (!value) {
|
|
throw new Error(
|
|
`Invalid value '${str}'. Expected one of: ${examples}`
|
|
);
|
|
}
|
|
return value;
|
|
},
|
|
description: `One of ${examples}`,
|
|
};
|
|
}
|