Gathering detailed insights and metrics for typed-assert
Gathering detailed insights and metrics for typed-assert
Gathering detailed insights and metrics for typed-assert
Gathering detailed insights and metrics for typed-assert
is-typed-array
Is this value a JS Typed Array? This module works cross-realm/iframe, does not depend on `instanceof` or mutable properties, and despite ES6 Symbol.toStringTag.
typed-array-byte-length
Robustly get the byte length of a Typed Array
typed-array-length
Robustly get the length of a Typed Array
which-typed-array
Which kind of Typed Array is this JavaScript value? Works cross-realm, without `instanceof`, and despite Symbol.toStringTag.
npm install typed-assert
99.7
Supply Chain
100
Quality
75.7
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
52 Stars
19 Commits
3 Forks
3 Watching
3 Branches
2 Contributors
Updated on 27 Aug 2024
TypeScript (91.43%)
JavaScript (8.57%)
Cumulative downloads
Total Downloads
Last day
-3.3%
569,135
Compared to previous day
Last week
1.7%
3,068,921
Compared to previous week
Last month
5.8%
12,969,603
Compared to previous month
Last year
29.3%
135,790,922
Compared to previous year
typed-assert
typed-assert
is a typesafe assertion library implementing the TS 3.7 Assertion Functions API, without external dependencies.
See the documentation.
zod
While this library does a fine job for most simple use cases, please consider using zod
if you need more complex assertions.
npm install typed-assert
or
yarn add typed-assert
typed-assert
promotes using unknown
instead of any
for "untrusted" values, e.g. user input, while still benefiting from incremental typing.
For example, JSON.stringify
returns any
, which is not typesafe. With typed-assert
, we can instead treat the result as unknown
and gradually check the contents at runtime and still get correct type inference:
1import * as t from "typed-assert"; 2 3const parseConfigFile = (file: string): { readonly a: string, readonly b: number } => { 4 const contents = JSON.parse(fs.readFileSync(file, { encoding: 'utf8'})) as unknown; 5 // contents is "unknown" instead of any, because we don't trust the input yet 6 t.isRecord(contents); 7 // contents is "Record<string, unknown>" 8 t.isString(contents.a); 9 // contents.a is "string" 10 t.isNumber(contents.b): 11 // contents.b is "number"; 12 return { 13 a: contents.a, 14 b: contents.b, 15 }; // correctly typed 16}
typed-assert
is both a compile-time and runtime assert library. It leverages the assertion function
feature of TypeScript to help the typechecker narrow the inferred types. In many cases, this significantly reduces the need to use any
, and promotes using unknown
instead.
For example:
1const u: unknown = {
2 a: "value",
3 b: 12,
4};
5
6chai.assert.typeOf(u, "object");
7// u is still "unknown"
8chai.assert.isNotNull(u);
9// u is still "unknown"
10chai.assert.typeof(u.a, "string");
11// TS Error (ts2571): u is "unknown"
12
13import * as t from "typed-assert";
14
15t.isRecord(u);
16// u is Record<string, unknown>
17t.isString(u.a);
18// u.a is string
19t.isNumber(u.b);
20// u.b is number
21
22const v: { a: string; b: number } = u;
23// no need to us `as ...`
typed-assert
comes with a set of common assertions, as well as assertion combinators and utilities.
See the documentation for a full reference.
1import * as t from "typed-assert";
2
3// Base asserts
4t.isExactly("a", "a");
5t.isNotUndefined(null);
6t.isNotNull(undefined);
7
8// Asserts combinators
9t.isOneOf("b", ["a", "b", "c"]);
10t.isArrayOf([2, 3, 4], t.isNumber);
11
12// Custom composite checks
13interface ICustomType {
14 readonly a: {
15 readonly b: "c";
16 readonly d: string;
17 };
18 readonly f?: number;
19}
20
21function assertCustomType(input: unknown): asserts input is ICustomType {
22 t.isRecordWithKeys(input, ["a", "f"]);
23 t.isRecordWithKeys(input.a, ["b", "d"]);
24 t.isExactly(input.a.b, "c");
25 t.isString(input.a.d);
26 t.isOption(input.f, t.isNumber);
27}
28
29const v = {
30 a: {
31 b: "c",
32 d: "",
33 },
34};
35assertCustomType(v);
This library also comes with a combinator to transform an assertion functions into a type guard function:
1const checkNumber = t.check(t.isNumber); 2checkNumber(1) === true; 3checkNumber("") === false;
It is especially convenient when combined with functional operations such as Array#filter
:
1const t = ["a", 3, "c", 4, null, 2] 2 .filter(t.check(t.isNumber)) 3 .map(x => x % 2 === 0 ? x : null) // x: number 4 .filter(t.check(t.isNotNull)); 5// t: number[] = [4, 2]
To encourage using asserts when dealing with untrusted JSON input, the following function is also exported:
1export const safeJsonParse = (json: string): unknown => 2 JSON.parse(json) as unknown;
This library is designed to work in the browser as well as in Node without external dependencies, and by default does not use the assert
module from the Node stdlib, so it ships with a very basic assert
implementation:
1export type WeakAssert = (input: unknown, message?: string) => void; 2 3export const defaultAssert: WeakAssert = (condition, message) => { 4 if (!condition) { 5 throw new TypeError(message); 6 } 7}; 8
It is however possible to configure the library to use a provided base assert
function, such as the native assert
module:
1import * as t from "typed-assert"; 2import nodeAssert from "assert"; 3 4t.setBaseAssert(nodeAssert);
Due to limitations in the typechecker, there are syntactic restrictions in how to define and use type assertion functions. For example, you can not dynamically define an assertion function, even if it looks like a static definition.
Thus the following code won't compile:
1function createIsExactly<T>(value: T): (input: unknown) => asserts input is T { 2 return function isExactly(input: unknown): asserts input is T { 3 t.isExactly(input, value); 4 }; 5} 6// No problem so far 7 8createIsExactly("a")(null); 9// Won't compile: 10// Assertions require the call target to be an 11// identifier or qualified name.ts(2776)
For similar reasons, it is not possible to use type-inferred arrow functions to define assertion functions:
1const isExactlyNull = (input: unknown): asserts input is null => assert(input === value); 2// No problem so far 3 4isExactlyNull("a", null): 5// Won't compile: 6// Assertions require the call target to be an 7// identifier or qualified name.ts(2776)
It is however possible to use arrow function with explicit typing of the left-hand operand:
1const isExactlyNull: (input: unknown) => asserts input is null = (input) => 2 assert(input === null); 3 4isExactlyNull("a"); 5// No problem
To simplify the implementation,
To simplify this pattern, this library also exports the Assert<Input, Output>
type as defined below:
1export type Assert<T> = ( 2 input: unknown, 3 message?: string, 4) => asserts input is T; 5 6const isExactlyNull: Assert<null> = (input) => assert(input === null); 7 8isExactlyNull("a"); 9// No problem
For convenience, this library also exports the following types, used internally:
1export type WeakAssert = (input: unknown, message?: string) => void; 2 3export type SubType<Input, Output> = Output extends Input ? Output : never; 4 5export type Assert<Input = unknown, Output = Input> = ( 6 input: Input, 7 message?: string, 8) => asserts input is SubType<Input, Output>; 9 10export type Check<Input = unknown, Output = Input> = ( 11 input: Input, 12) => input is SubType<Input, Output>;
This way we can write:
1const isExactlyNull: Assert<unknown, null> = (input) => 2 assert(input === null); 3 4isExactlyNull("a");
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
Found 2/17 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
license file not detected
Details
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
11 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More