tsafe
GitHub
  • 👋What is tsafe?
  • ⚙️How to import
  • assert
  • Equals
  • id
  • is
  • objectKeys
  • exclude
  • isAmong
  • symToStr
  • ReturnType
  • Parameters
  • Param0
  • typeGuard
  • capitalize/uncapitalize
  • MethodNames
  • isPromiseLike
  • flip
  • objectEntries
  • objectFromEntries
  • UnionToIntersection
  • 🚧withDefaults
  • 📉UnpackPromise
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub

isAmong

Let's say we have an union type like:

Names.ts
export const names = ["foo", "bar", "baz"] as const;
export type Name = typeof names[number];

isAmong enables to test if a given values is one of the names

import { isAmong } from "tsafe/isAmong";
import { names, type Names } from "./Names";

declare value: "foo" | "bar" | "something else";

if( isAmong(names, value) ){
  // Here value is of type "foo" | "bar"
  // (the intesection of the type of value before the test and Name)
}

If we just have the type and not the exhausive array:

import { assert, type Equals } from "tsafe/assert";
import { isAmong } from "tsafe/isAmong";
import type { Names } from "./Names";

const names = ["foo", "bar", "baz"] as const;

assert<Equals<typeof names, Names>>;

declare value: string;

if( isAmong(names, value) ){
   // Here value is of type Names
}
PreviousexcludeNextsymToStr

Last updated 6 months ago

Was this helpful?