Skip to main content
Module

x/unknownutil/mod.ts>isUnionOf

🦕 A lightweight utility pack for handling unknown type
Go to Latest
function isUnionOf
import { isUnionOf } from "https://deno.land/x/unknownutil@v3.18.0/mod.ts";

Return a type predicate function that returns true if the type of x is UnionOf<T>.

To enhance performance, users are advised to cache the return value of this function and mitigate the creation cost.

import { is } from "@core/unknownutil";

const isMyType = is.UnionOf([is.Number, is.String, is.Boolean]);
const a: unknown = 0;
if (isMyType(a)) {
  // a is narrowed to number | string | boolean
  const _: number | string | boolean = a;
}

Depending on the version of TypeScript and how values are provided, it may be necessary to add as const to the array used as preds. If a type error occurs, try adding as const as follows:

import { is } from "@core/unknownutil";

const preds = [is.Number, is.String, is.Boolean] as const;
const isMyType = is.UnionOf(preds);
const a: unknown = 0;
if (isMyType(a)) {
  // a is narrowed to number | string | boolean
  const _: number | string | boolean = a;
}

Type Parameters

T extends readonly [Predicate<unknown>, ...Predicate<unknown>[]]

Returns

Predicate<UnionOf<T>> & WithMetadata<IsUnionOfMetadata>