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.

TypescriptForm Validation

Code

typescriptsnippet
31 lines
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.test

Mechanics 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

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `formatLookupKey` at load time.