Type checking and asserting at runtime.
This is an isomorphic JavaScript Library, it should run on any modern JavaScript runtime.
📦 Scoped @xan105 packages are for my own personal use but feel free to use them.
import { isString } from "@xan105/types";
isString("foo") //trueUsing "type string":
import { is } from "@xan105/types";
is("string[]", ["foo", "bar"]); //true
is("function*", function*()=>{ yield "a" }); //trueReturn the given value when the condition is true otherwise throw a Type Error.
import { shouldString } from "@xan105/types";
const foo = shouldString("bar");or
import { should } from "@xan105/types";
const foo = should("string", "bar");Return the given value when the condition is true otherwise null.
import { asString } from "@xan105/types";
function foo(option = {}){
const options = {
bar: asString(option.bar) ?? "default value"
}
}or
import { as } from "@xan105/types";
function foo(option = {}){
const options = {
bar: as("string", option.bar) ?? "default value"
}
}npm install @xan105/types
💡 The bundled library and its minified version can be found in the ./dist folder.
Create an importmap and add it to your html:
<script type="importmap">
{
"imports": {
"@xan105/types": "./path/to/node_modules/@xan105/types/dist/types.min.js"
}
}
</script>
<script type="module">
import { isString } from "@xan105/types"
</script>
</body>
</html>List of supported "type string":
stringstrbooleanboolnumbernbrintegerintbigintobjectobjsymbolfunctionfuncfnpromisefunction*func*fn*regexpregexrregexerrorerrbufferuint8Arraysetmaparrayarr
You can add the suffix [] for an array, and add a number for fixed length array.
Example:
is("string[2]", ["foo", "bar"]); //truealias: isVoid()
alias: shouldVoid()
"Nullish": null or undefined
alias: isObject()
alias: asObject()
alias: shouldObject()
isArrayOf(fn: function, values: unknown[], option?: { args?: unknown[], length?: number } | unknown[]): boolean
asArrayOf(fn: function, values: unknown[], option?: { args?: unknown[], length?: number } | unknown[]): unknown[]|null
shouldArrayOf(fn: function, values: unknown[], option?: { args?: unknown[], length?: number } | unknown[]): unknown[]
If option is an array then args is assumed.
Creates a frozen, bidirectional numeric enum object, similar to TypeScript's enum.
Example:
const Colors = enumFrom({
RED: 1,
GREEN: 2,
BLUE: 3
});
// Both directions
console.log(Colors.GREEN); // 2
console.log(Colors[2]); // "GREEN"
// Immutable
Colors.GREEN = 99; // ❌ TypeError: Cannot assign to read only property