实现说明
模块级对象字面量,键名固定:retries。
使用要点
- 每一步打印都带着自己的标签:
union accepts partial:。
常见问题
需要标准库之外的东西吗?
除标准库外不引入任何东西——这个示例没有依赖。
核心语句
type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends (
arg: infer I,
) => void
代码示例
// A union of option objects becomes an intersection: every member's keys
// must be present at once. The contravariant function position flips the
// union, and a second inference round extracts it.
type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends (
arg: infer I,
) => void
? I
: never;
type ServerOptions = { retries: number } | { timeoutMs: number };
type Merged = UnionToIntersection<ServerOptions>;
const merged: Merged = { retries: 3, timeoutMs: 1_500 };
console.log(merged.retries, merged.timeoutMs);
// Without the helper, a plain union accepts any single member alone
const loose: ServerOptions = { retries: 3 };
console.log('union accepts partial:', 'retries' in loose && !('timeoutMs' in loose));