Skip to main content
Module

x/unknownutil/mod.ts

🦕 A lightweight utility pack for handling unknown type
Latest
import * as unknownutil from "https://deno.land/x/unknownutil@v3.18.0/mod.ts";

A utility pack for handling unknown type.

Usage

It provides is module for type predicate functions and assert, ensure, and maybe helper functions.

is*

Type predicate function is a function which returns true if a given value is expected type. For example, isString (or is.String) returns true if a given value is string.

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

const a: unknown = "Hello";
if (is.String(a)) {
  // 'a' is 'string' in this block
}

For more complex types, you can use is*Of (or is.*Of) functions like:

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

const isArticle = is.ObjectOf({
  title: is.String,
  body: is.String,
  refs: is.ArrayOf(
    is.UnionOf([
      is.String,
      is.ObjectOf({
        name: is.String,
        url: is.String,
      }),
    ]),
  ),
  createTime: is.OptionalOf(is.InstanceOf(Date)),
  updateTime: is.OptionalOf(is.InstanceOf(Date)),
});

// Infer the type of `Article` from the definition of `isArticle`
type Article = PredicateType<typeof isArticle>;

const a: unknown = {
  title: "Awesome article",
  body: "This is an awesome article",
  refs: [{ name: "Deno", url: "https://deno.land/" }, "https://github.com"],
};
if (isArticle(a)) {
  // a is narrowed to the type of `isArticle`
  console.log(a.title);
  console.log(a.body);
  for (const ref of a.refs) {
    if (is.String(ref)) {
      console.log(ref);
    } else {
      console.log(ref.name);
      console.log(ref.url);
    }
  }
}

Additionally, you can manipulate the predicate function returned from isObjectOf with isPickOf, isOmitOf, isPartialOf, and isRequiredOf similar to TypeScript's Pick, Omit, Partial, Required utility types.

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

const isArticle = is.ObjectOf({
  title: is.String,
  body: is.String,
  refs: is.ArrayOf(
    is.UnionOf([
      is.String,
      is.ObjectOf({
        name: is.String,
        url: is.String,
      }),
    ]),
  ),
  createTime: is.OptionalOf(is.InstanceOf(Date)),
  updateTime: is.OptionalOf(is.InstanceOf(Date)),
});

const isArticleCreateParams = is.PickOf(isArticle, ["title", "body", "refs"]);
// is equivalent to
//const isArticleCreateParams = is.ObjectOf({
//  title: is.String,
//  body: is.String,
//  refs: is.ArrayOf(
//    is.UnionOf([
//      is.String,
//      is.ObjectOf({
//        name: is.String,
//        url: is.String,
//      }),
//    ]),
//  ),
//});

const isArticleUpdateParams = is.OmitOf(isArticleCreateParams, ["title"]);
// is equivalent to
//const isArticleUpdateParams = is.ObjectOf({
//  body: is.String,
//  refs: is.ArrayOf(
//    is.UnionOf([
//      is.String,
//      is.ObjectOf({
//        name: is.String,
//        url: is.String,
//      }),
//    ]),
//  ),
//});

const isArticlePatchParams = is.PartialOf(isArticleUpdateParams);
// is equivalent to
//const isArticlePatchParams = is.ObjectOf({
//  body: is.OptionalOf(is.String),
//  refs: is.OptionalOf(is.ArrayOf(
//    is.UnionOf([
//      is.String,
//      is.ObjectOf({
//        name: is.String,
//        url: is.String,
//      }),
//    ]),
//  )),
//});

const isArticleAvailableParams = is.RequiredOf(isArticle);
// is equivalent to
//const isArticlePutParams = is.ObjectOf({
//  body: is.String,
//  refs: is.ArrayOf(
//    is.UnionOf([
//      is.String,
//      is.ObjectOf({
//        name: is.String,
//        url: is.String,
//      }),
//    ]),
//  ),
//  createTime: is.InstanceOf(Date),
//  updateTime: is.InstanceOf(Date),
//});

If you need an union type or an intersection type, use isUnionOf and isIntersectionOf like:

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

const isFoo = is.ObjectOf({
  foo: is.String,
});

const isBar = is.ObjectOf({
  bar: is.String,
});

const isFooOrBar = is.UnionOf([isFoo, isBar]);
// { foo: string } | { bar: string }

const isFooAndBar = is.IntersectionOf([isFoo, isBar]);
// { foo: string } & { bar: string }

assert

The assert function does nothing if a given value is expected type. Otherwise, it throws an AssertError exception like:

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

const a: unknown = "Hello";

// `assert` does nothing or throws an `AssertError`
assert(a, is.String);
// a is now narrowed to string

// With custom message
assert(a, is.String, { message: "a must be a string" });

ensure

The ensure function return the value as-is if a given value is expected type. Otherwise, it throws an AssertError exception like:

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

const a: unknown = "Hello";

// `ensure` returns `string` or throws an `AssertError`
const _: string = ensure(a, is.String);

// With custom message
const __: string = ensure(a, is.String, { message: "a must be a string" });

maybe

The maybe function return the value as-is if a given value is expected type. Otherwise, it returns undefined that suites with nullish coalescing operator (??) like:

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

const a: unknown = "Hello";

// `maybe` returns `string | undefined` so it suites with `??`
const _: string = maybe(a, is.String) ?? "default value";

Classes

Represents an error that occurs when an assertion fails.

Functions

Asserts that the given value satisfies the provided predicate.

Ensures that the given value satisfies the provided predicate.

Get metadata from the given value

Get metadata from a predicate factory function.

f
isAllOf
deprecated

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

Assume x is anyand always returntrueregardless of the type ofx`.

Return true if the type of x is unknown[].

Return a type predicate function that returns true if the type of x is T[].

Return true if the type of x is function (async function).

Return true if the type of x is bigint.

Return true if the type of x is boolean.

Return true if the type of x is function.

Return true if the type of x is instance of ctor.

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

Return a type predicate function that returns true if the type of x is a literal type of pred.

Return a type predicate function that returns true if the type of x is one of literal type in preds.

Return true if the type of x is Map<unknown, unknown>.

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

Return true if the type of x is null.

Return true if the type of x is null or undefined.

Return true if the type of x is number.

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

Return a type predicate function that returns true if the type of x is Omit<ObjectOf<T>, K>.

f
isOneOf
deprecated

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

Return true if the type of predicate function x is annotated as Optional

Return an Optional annotated type predicate function that returns true if the type of x is T or undefined.

Return a type predicate function that returns true if the type of x is ParametersOf<T> or ParametersOf<T, E>.

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

Return a type predicate function that returns true if the type of x is Pick<ObjectOf<T>, K>.

Return true if the type of x is Primitive.

Return true if the type of predicate function x is annotated as Readonly

Return an Readonly annotated type predicate function that returns true if the type of x is T.

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

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

Return true if the type of x satisfies Record<PropertyKey, unknown>.

f
isRecordLike
deprecated

Return true if the type of x is like Record<PropertyKey, unknown>.

f
isRecordLikeOf
deprecated

Return a type predicate function that returns true if the type of x satisfies Record<K, T>.

Return true if the type of x is an object instance that satisfies Record<PropertyKey, unknown>.

Return a type predicate function that returns true if the type of x is an Object instance that satisfies Record<K, T>.

Return a type predicate function that returns true if the type of x satisfies Record<K, T>.

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

Return true if the type of x is Set<unknown>.

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

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

Return true if the type of x is string.

Return true if the type of x is symbol.

Return true if the type of x is function (non async function).

Return a type predicate function that returns true if the type of x is TupleOf<T> or TupleOf<T, E>.

Return true if the type of x is undefined.

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

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

Assume x is unknown and always return true regardless of the type of x.

Return an Optional un-annotated type predicate function that returns true if the type of x is T.

Return an Readonly un-annotated type predicate function that returns true if the type of x is T.

Returns the input value if it satisfies the provided predicate, or undefined otherwise.

Sets the factory function used to generate assertion error messages.

Set metadata to a predicate factory function.

Type Aliases

Get typeof the metadata

A type predicate function.

Metadata of a predicate factory function.

A type predicated by Predicate.

A type that has metadata.