0797c7692bbf53202d2cbc132a2bda1728ebd3a5701f54c90e797b5c4d7f7bee5ed2b065ed2e5667b57ee2790de04cf315384a5c92311229d9c97edd535241 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. /**
  2. Create a type that makes the given keys required. The remaining keys are kept as is. The sister of the `SetOptional` type.
  3. Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are required.
  4. @example
  5. ```
  6. import {SetRequired} from 'type-fest';
  7. type Foo = {
  8. a?: number;
  9. b: string;
  10. c?: boolean;
  11. }
  12. type SomeRequired = SetRequired<Foo, 'b' | 'c'>;
  13. // type SomeRequired = {
  14. // a?: number;
  15. // b: string; // Was already required and still is.
  16. // c: boolean; // Is now required.
  17. // }
  18. ```
  19. */
  20. export type SetRequired<BaseType, Keys extends keyof BaseType = keyof BaseType> =
  21. // Pick just the keys that are not required from the base type.
  22. Pick<BaseType, Exclude<keyof BaseType, Keys>> &
  23. // Pick the keys that should be required from the base type and make them required.
  24. Required<Pick<BaseType, Keys>> extends
  25. // If `InferredType` extends the previous, then for each key, use the inferred type key.
  26. infer InferredType
  27. ? {[KeyType in keyof InferredType]: InferredType[KeyType]}
  28. : never;