实现说明
要求可选键至少提供一个的联合约束可以归结为函数 formatLookupKey。
使用要点
- 原生工具链自身便已足够跑通——执行期间不会发生三方包依赖解析。
- 每一步打印都带着自己的标签:
single key:、multi key :。
常见问题
有需要管理的依赖吗?
没有。无需声明或安装任何依赖。 文件在加载时定义 formatLookupKey。
签名一览:function formatLookupKey(query: ValidLookup)
核心语句
return `${query.tenant} -> ${parts.join(', ')}`;
代码示例
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));