Require At Least One Optional Key
Build a mapped union helper RequireAtLeastOne<T, K> so callers must supply at least one optional identifier key while rejecting empty objects at compile time.
Code
interface LookupInput {
tenant: string;
userId?: string;
email?: string;
externalRef?: string;
}
// Keep non-target fields as-is; require at least one key from `Keys`
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> =
Pick<T, Exclude<keyof T, Keys>> &
{
[K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>;
}[Keys];
type ValidLookup = RequireAtLeastOne<LookupInput, 'userId' | 'email' | 'externalRef'>;
function formatLookupKey(query: ValidLookup): string {
const parts: string[] = [];
if (query.userId !== undefined) parts.push(`id=${query.userId}`);
if (query.email !== undefined) parts.push(`email=${query.email}`);
if (query.externalRef !== undefined) parts.push(`ref=${query.externalRef}`);
return `${query.tenant} -> ${parts.join(', ')}`;
}
const byEmail: ValidLookup = { tenant: 'acme', email: 'ada@example.test' };
const byBoth: ValidLookup = { tenant: 'acme', userId: 'u-42', email: 'ada@example.test' };
// Compile error: missing all of 'userId' | 'email' | 'externalRef'
// const missingKey: ValidLookup = { tenant: 'acme' };
console.log('single key:', formatLookupKey(byEmail));
console.log('multi key :', formatLookupKey(byBoth));Output
Captured from a sandboxed run of this snippet in the build pipeline.
single key: acme -> email=ada@example.test
multi key : acme -> id=u-42, email=ada@example.testMechanics trace — Require At Least One Optional Key
Runtime behavior concentrates closely inside callable formatLookupKey — everything else is wiring.
Points of care
- Stock toolchain handles everything standalone — zero external package resolution runs anywhere.
Using it
The entry-point signature is function formatLookupKey(query: ValidLookup)
Stdout entries begin explicitly with — single key:, multi key : — when the file runs.
Key statements
return `${query.tenant} -> ${parts.join(', ')}`;
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `formatLookupKey` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.