type-guards.ts 690 B

123456789101112131415
  1. /**
  2. * A variant of Array.includes that allows us to use it as a type guard.
  3. *
  4. * It allows us to narrow the type of an arbitrary T to U if it is one of U[].
  5. *
  6. * TypeScript currently doesn't allow us to use the standard Array.includes as a
  7. * type guard for checking if an arbitrary string is one of the known set of
  8. * values. This issue and this workaround is mentioned here:
  9. * - https://github.com/microsoft/TypeScript/issues/48247
  10. * - https://github.com/microsoft/TypeScript/issues/26255#issuecomment-502899689
  11. */
  12. export function includes<T, U extends T>(us: readonly U[], t: T): t is U {
  13. // @ts-expect-error @typescript-eslint/no-unsafe-argument
  14. return us.includes(t);
  15. }