UNPKG

type-fest

Version:

A collection of essential TypeScript types

58 lines (48 loc) • 2.19 kB
import type {KeysOfUnion} from './keys-of-union.d.ts'; import type {Except} from './except.d.ts'; import type {_RequireExactlyOneOfOne} from './require-exactly-one.d.ts'; import type {DeduplicatedKeys, IfNotAnyOrNever, KeyAliases} from './internal/index.d.ts'; import type {RequireNone} from './require-none.d.ts'; import type {If} from './if.d.ts'; import type {IsAny} from './is-any.d.ts'; import type {IsNever} from './is-never.d.ts'; /** Create a type that requires exactly one of the given keys or none of the given keys, while keeping the remaining keys as is. @example ``` import type {RequireOneOrNone} from 'type-fest'; type Responder = RequireOneOrNone<{ text: () => string; json: () => string; secure: boolean; }, 'text' | 'json'>; const responder1: Responder = { secure: true, }; const responder2: Responder = { text: () => '{"message": "hi"}', secure: true, }; const responder3: Responder = { json: () => '{"message": "ok"}', secure: true, }; ``` @category Object */ // `IfNotAnyOrNever` comes first, so an `any` `ObjectType` stays `any` even when `KeysType` is generic. export type RequireOneOrNone<ObjectType, KeysType extends KeysOfUnion<ObjectType> = KeysOfUnion<ObjectType>> = IfNotAnyOrNever<ObjectType, { ifNot: If<IsNever<KeysType>, ObjectType, _RequireOneOrNone<ObjectType, If<IsAny<KeysType>, KeysOfUnion<ObjectType>, 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 type ever saw it. type _RequireOneOrNone<ObjectType, KeysType extends PropertyKey> = ObjectType extends unknown ? ( | _RequireExactlyOneOfOne<ObjectType, KeysType & keyof ObjectType, KeysType & keyof ObjectType> | RequireNone<KeysType & keyof ObjectType> ) & Except<ObjectType, KeysType & keyof ObjectType> // Keep unselected declared fields even when an index signature covers them. & RequireNone<Exclude<DeduplicatedKeys<KeysType>, KeyAliases<keyof ObjectType>>> // Deduplicate string aliases of declared numeric and enum keys before forbidding other members' keys. : never; export {};