9aaea0f31cf37fd693ded8307edfba9dfa4f8e550db2a52fb3dd8655c26beeea4824a497fda328968232985d140f64e4d5c989ebeeacd0e0d02d66c91e5852 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. /**
  2. Create a type that makes the given keys optional. The remaining keys are kept as is. The sister of the `SetRequired` 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 optional.
  4. @example
  5. ```
  6. import {SetOptional} from 'type-fest';
  7. type Foo = {
  8. a: number;
  9. b?: string;
  10. c: boolean;
  11. }
  12. type SomeOptional = SetOptional<Foo, 'b' | 'c'>;
  13. // type SomeOptional = {
  14. // a: number;
  15. // b?: string; // Was already optional and still is.
  16. // c?: boolean; // Is now optional.
  17. // }
  18. ```
  19. */
  20. export type SetOptional<BaseType, Keys extends keyof BaseType = keyof BaseType> =
  21. // Pick just the keys that are not optional from the base type.
  22. Pick<BaseType, Exclude<keyof BaseType, Keys>> &
  23. // Pick the keys that should be optional from the base type and make them optional.
  24. Partial<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;