@sinclair/typebox
Version:
Json Schema Type Builder with Static Type Resolution for TypeScript
33 lines (32 loc) • 1.27 kB
JavaScript
import { TemplateLiteralGenerate } from '../template-literal/index.mjs';
// ------------------------------------------------------------------
// TypeGuard
// ------------------------------------------------------------------
import { IsTemplateLiteral, IsUnion, IsLiteral, IsNumber, IsInteger } from '../guard/kind.mjs';
// prettier-ignore
function FromTemplateLiteral(templateLiteral) {
const result = TemplateLiteralGenerate(templateLiteral);
return result.map(S => S.toString());
}
// prettier-ignore
function FromUnion(type) {
const result = [];
for (const left of type)
result.push(...IndexPropertyKeys(left));
return result;
}
// prettier-ignore
function FromLiteral(T) {
return ([T.toString()] // TS 5.4 observes TLiteralValue as not having a toString()
);
}
/** Returns a tuple of PropertyKeys derived from the given TSchema */
// prettier-ignore
export function IndexPropertyKeys(type) {
return [...new Set((IsTemplateLiteral(type) ? FromTemplateLiteral(type) :
IsUnion(type) ? FromUnion(type.anyOf) :
IsLiteral(type) ? FromLiteral(type.const) :
IsNumber(type) ? ['[number]'] :
IsInteger(type) ? ['[number]'] :
[]))];
}