import type {KeysOfUnion} from './keys-of-union.d.ts'; import type {Except} from './except.d.ts'; import type {If} from './if.d.ts'; import type {IfNotAnyOrNever, RequireAll} from './internal/index.d.ts'; import type {IsAny} from './is-any.d.ts'; import type {IsNever} from './is-never.d.ts'; /** Create a type that requires at least one of the given keys, while keeping the remaining keys as is. Note: For a union, a member that has none of the given keys is kept as it is. For example, with `{kind: 'circle'; radius?: number; diameter?: number} | {kind: 'square'; side: number}` and the keys `'radius' | 'diameter'`, a square needs neither key. Note: An index signature cannot be required, so if the keys include one (for example, the default keys of `Record`), the type accepts `{}`. Note: A check of a key for `undefined` does not narrow the type, because TypeScript only narrows a union through a property with a literal type. For example, with `{a: string; b: string}`, `value.a ?? value.b` is `string | undefined`. Use the `in` operator instead: `'a' in value ? value.a : value.b`. @example ``` import type {RequireAtLeastOne} from 'type-fest'; type Responder = { text?: () => string; json?: () => string; secure?: boolean; }; const responder: RequireAtLeastOne = { json: () => '{"message": "ok"}', secure: true, }; ``` @category Object */ export type RequireAtLeastOne< ObjectType, KeysType extends KeysOfUnion = KeysOfUnion, > = IfNotAnyOrNever, never, _RequireAtLeastOne, KeysOfUnion, KeysType>>>; }>; // The keys are intersected with each member's own inside the distribution, because `keyof` of a union is the intersection of its members' keys, so a key only one member has would otherwise be dropped before the mapped type ever saw it. type _RequireAtLeastOne = ObjectType extends unknown // A member that has none of the keys is left as it is. ? If, ObjectType, _RequireAtLeastOneOfOne> : never; export type _RequireAtLeastOneOfOne = { // For each `Key` in `KeysType` make a mapped type: [Key in KeysType]-?: RequireAll; // 1. Make `Key`'s type required }[KeysType] & {[Key in KeysType]?: ObjectType[Key]} // 2. Share the optional selected fields; each alternative's required key overrides its optional copy. & Except; // 3. Add the remaining keys not in `KeysType` export {};