import { isParametersOf } from "https://deno.land/x/unknownutil@v3.18.0/is.ts";
Return a type predicate function that returns true
if the type of x
is ParametersOf<T>
or ParametersOf<T, E>
.
This is similar to TupleOf<T>
or TupleOf<T, E>
, but if is.OptionalOf()
is specified at the trailing, the trailing elements becomes optional and makes variable-length tuple.
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.ParametersOf([
is.Number,
is.OptionalOf(is.String),
is.Boolean,
is.OptionalOf(is.Number),
is.OptionalOf(is.String),
is.OptionalOf(is.Boolean),
] as const);
const a: unknown = [0, undefined, "a"];
if (isMyType(a)) {
// a is narrowed to [number, string | undefined, boolean, number?, string?, boolean?]
const _: [number, string | undefined, boolean, number?, string?, boolean?] = a;
}
With predElse
:
import { is } from "@core/unknownutil";
const isMyType = is.ParametersOf(
[
is.Number,
is.OptionalOf(is.String),
is.OptionalOf(is.Boolean),
] as const,
is.ArrayOf(is.Number),
);
const a: unknown = [0, "a", true, 0, 1, 2];
if (isMyType(a)) {
// a is narrowed to [number, string?, boolean?, ...number[]]
const _: [number, string?, boolean?, ...number[]] = 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 predTup
. If a type error occurs, try adding as const
as follows:
import { is } from "@core/unknownutil";
const predTup = [is.Number, is.String, is.OptionalOf(is.Boolean)] as const;
const isMyType = is.ParametersOf(predTup);
const a: unknown = [0, "a"];
if (isMyType(a)) {
// a is narrowed to [number, string, boolean?]
const _: [number, string, boolean?] = a;
}
Type Parameters
T extends readonly [...Predicate<unknown>[]]
Parameters
predTup: T
Returns
Predicate<ParametersOf<T>> & WithMetadata<IsParametersOfMetadata>
Returns
Predicate<[...ParametersOf<T>, ...PredicateType<E>]> & WithMetadata<IsParametersOfMetadata>