diff --git a/.eslintignore b/.eslintignore
deleted file mode 100644
index ae27c75..0000000
--- a/.eslintignore
+++ /dev/null
@@ -1,18 +0,0 @@
-.github
-.vscode
-
-coverage
-dist
-docs
-node_modules
-storybook-static
-
-.eslintrc.js
-.prettierrc.js
-babel.config.js
-fallback-react.d.ts
-tailwind.config.js
-postcss.config.js
-tsconfig.json
-
-.cobaco
diff --git a/.eslintrc.cjs b/.eslintrc.cjs
deleted file mode 100644
index afb71ad..0000000
--- a/.eslintrc.cjs
+++ /dev/null
@@ -1,213 +0,0 @@
-/**
- * @type {import('@typescript-eslint/experimental-utils').TSESLint.Linter.Config}
- */
-const config = {
- extends: [
- 'eslint:recommended',
- 'plugin:@typescript-eslint/recommended',
- 'prettier'
- ],
- globals: {
- es2020: true
- },
- plugins: ['import'],
- rules: {
- /**
- * 'max-lines' .. error
- *
- * 各ファイルは 150 行を上限とする. このカウントにコメントや空行は含めない.
- */
- 'max-lines': [
- 'error',
- {
- max: 150,
- skipComments: true,
- skipBlankLines: true
- }
- ],
-
- /**
- * 'max-lines-per-function' .. error
- *
- * function は 50 行を上限とする. このカウントにコメントや空行は含めない.
- */
- 'max-lines-per-function': [
- 'error',
- {
- skipBlankLines: true,
- skipComments: true
- }
- ],
-
- /**
- * 'max-statements' .. warning
- *
- * function 内で定義する statement (e.g. `var` `let` `const`) は 10 個を超える場合は警告とする.
- * 単純に冗長な手続きを書かざるを得ない場合などがあり、このルールは厳密に守ることが出来ない.
- * 言い換えれば、このケースで警告が出ている場合は、 "複雑なコード" であることを意識すること.
- *
- * e.g.
- * ```ts
- * function foo() {
- * var foo1 = 1;
- * var foo2 = 2;
- * var foo3 = 3;
- * var foo4 = 4;
- * var foo5 = 5;
- * var foo6 = 6;
- * var foo7 = 7;
- * var foo8 = 8;
- * var foo9 = 9;
- * var foo10 = 10;
- *
- * var foo11 = 11; // Too many.
- * }
- * ```
- */
- 'max-statements': ['warn', { max: 20 }],
-
- /**
- * 'no-else-return' .. error
- * else ブロック及び、 else-if ブロックにおける return を禁止する.
- * 具体的には、以下の書き方が正となる
- *
- * e.g.
- * ```ts
- * function hoge() {
- * if (conditionA) {
- * return 1
- * }
- * if (conditionB) {
- * return 2
- * }
- *
- * return 3
- * }
- * ```
- */
- 'no-else-return': ['error', { allowElseIf: false }],
-
- /**
- * 'max-depth' .. error (max 4 -> 3)
- *
- * 入れ子のレベルを最大 3 段階に制限する.
- * 深ければ深いほど可読性が悪化するため.
- *
- * e.g.
- * ```ts
- * function hoge() {
- * if (true) {
- * // Nested 1 deep
- * if (true) {
- * // Nested 2 deep
- * if (true) {
- * // Nested 3 deep
- * if (true) {
- * // Nested 4 deep (ERROR!)
- * }
- * }
- * }
- * }
- * }
- * ```
- */
- 'max-depth': [
- 'error',
- {
- max: 3
- }
- ],
-
- /**
- * '@typescript-eslint/array-type' .. array-simple モード
- * TSでArrayを記載する際に、 シンプルな型なら Hoge[] を強制、複雑な型なら Array<...> を強制する
- */
- '@typescript-eslint/array-type': [
- 'warn',
- {
- default: 'array-simple'
- }
- ],
-
- /**
- * '@typescript-eslint/explicit-module-boundary-types' .. warn
- * すべての関数には、引数と返り値の型をつくりましょう。
- * (returnしないなら省略可能)
- */
- '@typescript-eslint/explicit-module-boundary-types': 'warn',
-
- /**
- * '@typescript-eslint/no-unused-vars' .. error
- * 未使用の変数はすべて消しましょう。
- * ただし、 "_" から始まる変数名については "明示的に未使用である宣言として扱い" このルールを無効とする
- */
- '@typescript-eslint/no-unused-vars': [
- 'error',
- {
- argsIgnorePattern: '^_',
- ignoreRestSiblings: true
- }
- ],
-
- /**
- * '@typescript-eslint/no-namespace' .. 無効化
- * TS の構文で namespace を使っても良い
- *
- * [背景]
- * 使えたほうが便利なケースがある
- */
- '@typescript-eslint/no-namespace': 'off',
-
- /**
- * '@typescript-eslint/no-non-null-assertion' .. 無効化
- * 非nullアサーション構文の利用を禁止しない
- *
- * [背景]
- * これを守り切るには高めのTS力が試されるため
- */
- '@typescript-eslint/no-non-null-assertion': 'off',
-
- /**
- * '@typescript-eslint/ban-types' .. 基本は error, ただし `{}` のみ許可
- * 非推奨の型の利用を禁止する (e.g. `string` ではなく `String`, Function, Object など)
- *
- * [背景]
- * typescript 4.8 のリリース内容に合わせての対応
- * → https://devblogs.microsoft.com/typescript/announcing-typescript-4-8/
- *
- * `{}` とは、 null, undefined とは異なる任意の型であることを示す.
- * 4.8 バージョンアップによって利便性が向上したため、利用を全面的に許可する
- */
- '@typescript-eslint/ban-types': [
- 'error',
- {
- types: {
- '{}': false
- },
- extendDefaults: true
- }
- ],
-
- /**
- * 'import/extensions' .. 一部の拡張子のみ、 import 文での拡張子の記載を強制する
- *
- * [背景]
- * Nuxt Server Side Process にて、 js ファイルは拡張子がないと参照できないため.
- */
- 'import/extensions': [
- 'error',
- {
- js: 'always',
- mjs: 'always',
- cjs: 'always',
- json: 'always',
- css: 'always',
- sass: 'always',
- scss: 'always',
- vue: 'always'
- }
- ]
- }
-}
-
-module.exports = config
diff --git a/.gitignore b/.gitignore
index 727fd4d..8a02869 100644
--- a/.gitignore
+++ b/.gitignore
@@ -109,3 +109,6 @@ dist
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
+
+# generated types
+.astro
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
deleted file mode 100644
index fbcd190..0000000
--- a/.pre-commit-config.yaml
+++ /dev/null
@@ -1,22 +0,0 @@
-repos:
- - repo: https://github.com/pre-commit/mirrors-eslint
- rev: v8.54.0
- hooks:
- - id: eslint
-
- - repo: https://github.com/pre-commit/mirrors-prettier
- rev: v3.1.0 # use 2.8.0
- hooks:
- - id: prettier
- additional_dependencies:
- - prettier@2.8.0
-
- - repo: https://github.com/renovatebot/pre-commit-hooks
- rev: 37.61.4
- hooks:
- - id: renovate-config-validator
-
- - repo: https://github.com/rhysd/actionlint
- rev: v1.6.26
- hooks:
- - id: actionlint
diff --git a/.prettierignore b/.prettierignore
deleted file mode 100644
index ae27c75..0000000
--- a/.prettierignore
+++ /dev/null
@@ -1,18 +0,0 @@
-.github
-.vscode
-
-coverage
-dist
-docs
-node_modules
-storybook-static
-
-.eslintrc.js
-.prettierrc.js
-babel.config.js
-fallback-react.d.ts
-tailwind.config.js
-postcss.config.js
-tsconfig.json
-
-.cobaco
diff --git a/.prettierrc.cjs b/.prettierrc.cjs
deleted file mode 100644
index 0901b5a..0000000
--- a/.prettierrc.cjs
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * @type {import('prettier').Config}
- */
-const config = {
- semi: false,
- arrowParens: 'always',
- singleQuote: true,
- trailingComma: 'none',
- htmlWhitespaceSensitivity: 'ignore',
- bracketSameLine: true,
- singleAttributePerLine: true,
- overrides: [
- {
- files: '*.ts',
- options: {
- printWidth: 100
- }
- }
- ]
-}
-module.exports = config
diff --git a/.vscode/project.code-workspace b/.vscode/project.code-workspace
index 6251b09..5dca760 100644
--- a/.vscode/project.code-workspace
+++ b/.vscode/project.code-workspace
@@ -1,3 +1,46 @@
{
- "folders": [{ "path": ".." }]
+ "folders": [{ "path": ".." }, { "path": "docs", "name": "@docs" }],
+ "extensions": {
+ "recommendations": [
+ "astro-build.astro-vscode",
+ "DavidAnson.vscode-markdownlint",
+ "biomejs.biome",
+ "ZixuanChen.vitest-explorer"
+ ]
+ },
+ "launch": {
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "command": "./node_modules/.bin/astro dev",
+ "name": "Development server",
+ "request": "launch",
+ "type": "node-terminal"
+ }
+ ]
+ },
+ "settings": {
+ "typescript.tsdk": "node_modules/typescript/lib",
+
+ "[javascript]": {
+ "editor.defaultFormatter": "biomejs.biome"
+ },
+
+ "[typescript]": {
+ "editor.defaultFormatter": "biomejs.biome"
+ },
+
+ "[astro]": {
+ "editor.defaultFormatter": "biomejs.biome"
+ },
+
+ "editor.codeActionsOnSave": {
+ "quickfix.biome": "explicit",
+ "source.organizeImports.biome": "explicit"
+ },
+
+ "markdownlint.config": {
+ "no-duplicate-heading": false
+ }
+ }
}
diff --git a/docs/CONTROBUTING.md b/CONTROBUTING.md
similarity index 100%
rename from docs/CONTROBUTING.md
rename to CONTROBUTING.md
diff --git a/README.md b/README.md
index 5877d15..dc20a27 100644
--- a/README.md
+++ b/README.md
@@ -3,21 +3,24 @@
[![Release](https://github.com/hacomono-lib/type-assurer/actions/workflows/release.yml/badge.svg)](https://github.com/hacomono-lib/type-assurer/actions/workflows/release.yml)
[![Test](https://github.com/hacomono-lib/type-assurer/actions/workflows/test.yml/badge.svg)](https://github.com/hacomono-lib/type-assurer/actions/workflows/test.yml)
-`type-assurer` is a TypeScript-first type checking library, providing compatibility with lodash's type guard functions while ensuring type safety. Designed with ESModules in mind, it allows for tree-shaking to minimize bundle sizes.
+`type-assurer` is a TypeScript-first type checking library. Designed with ESModules in mind, it allows for tree-shaking to minimize bundle sizes.
## Features
-- Compatible with lodash type guard functions
- TypeScript-first implementation with accurate type inference
- ESModule ready for tree-shaking and bundle size optimization
- No external dependencies
-- A collection of 7 type guard functions:
- a. isString - Similar to lodash's type guard functions
- b. assertString - Provides TypeScript's type assertion feature
- c. ensureString - Evaluates the argument's type and returns the value if the type guard passes, otherwise throws an exception
- d. fallbackString - Evaluates the first argument's type and returns the value if the type guard passes, otherwise returns the second argument's value
+- 7 type guard functions:
+ a. `isFoo` (e.g. isString) - type guard functions
+ b. `assertFoo` (e.g. assertString) - Provides TypeScript's type assertion feature
+ c. `ensureFoo` (e.g. ensureString) - Evaluates the argument's type and returns the value if the type guard passes, otherwise throws an exception
+ d. `fallbackFoo` (e.g. fallbackString) - Evaluates the first argument's type and returns the value if the type guard passes, otherwise returns the second argument's value
- The reversed versions
- Generator provided for custom type guards for non-primitive types
+- 2 type modification functions:
+ a. `coerceFoo` (e.g. coerceNumber) - Evaluates the argument's type and returns the value if the type guard passes, otherwise throws an exception
+ b. `fixFoo` (e.g. fixNumber) - Evaluates the first argument's type and returns the value if the type guard passes, otherwise returns the second argument's value
+ - If there is a type check for a parsable or modifiable value, there is a corresponding function. (e.g. NumberParsable, Jsonifiable, etc.)
## Installation
@@ -31,15 +34,13 @@ The library provides 8 utility functions for each type guard, such as `isString`
And, note that `fallbackNotNil` can be replaced with the `??` operator. Functions that can be simplified using standard JavaScript expressions, like this example, are not targeted for implementation.
-### is, isNot
+### is
Functions such as `is` simply provide type guards that can be used in conditional branches.
```typescript
import { isString } from 'type-assurer'
-declare const value: unknown
-
if (isString(value)) {
console.log(`This is a string: ${value}`)
} else {
@@ -52,13 +53,20 @@ Functions such as `isNot` are useful in cases that require a type guard function
```typescript
import { isNotNil } from 'type-assurer'
-declare const values: string | null
-
const result = values.filter(isNotNil)
// ^? string[]
```
-### assert, assertNot
+Also, type guard functions such as `isXxx` are implemented in the form of `not(isXxx)`.
+If you have implemented your own type guard, you can use the `not` function directly.
+
+```typescript
+import { not } from 'type-assurer'
+
+const result = values.filter(not(isFoo))
+```
+
+### assert
Functions with names like `assert` `assertNot` are type assertion functions.
If the type check does not pass, it throws a TypeError.
@@ -74,7 +82,7 @@ assertString(value, 'Value must be a string')
// No error if value is a string, otherwise throws an error with the message "Value must be a string"
```
-### ensure, ensureNot
+### ensure
Functions with names like `ensure` `ensureNot` are type assertion functions, but return the same value if the type check passes.
It is convenient to write type assertions on a single line.
@@ -91,7 +99,7 @@ const value = ensureString(await fetchData(), 'Value must be a string')
// No error if fetchData returns a string, otherwise throws an error with the message "Value must be a string"
```
-### fallback, fallbackNot
+### fallback
Functions like `fallback` `fallbackNot` are type modification functions.
@@ -107,6 +115,45 @@ const value = fallbackString(await fetchData(), 'default')
// Returns value if it's a string, otherwise returns the fallbackValue
```
+### coerce
+
+Functions like `coerce` are type modification functions.
+
+If there is a type check for a parsable or modifiable value, there is a corresponding function. (e.g. NumberParsable, Jsonifiable, etc.)
+
+This function returns the modifiable value if the type is parsable, otherwise it throws an exception.
+
+```typescript
+import { coerceNumber } from 'type-assurer'
+
+const value1 = coerceNumber('123')
+// ^? 123
+
+const value2 = coerceNumber('abc')
+// thrown TypeAssertionError
+```
+
+### fix
+
+Functions like `fix` are type modification functions.
+
+If there is a type check for a parsable or modifiable value, there is a corresponding function. (e.g. NumberParsable, Jsonifiable, etc.)
+
+This function returns the modifiable value if the type is parsable, otherwise it returns the fallback value specified in the second argument.
+
+```typescript
+import { fixNumber } from 'type-assurer'
+
+const value1 = fixNumber('123')
+// ^? 123
+
+const value2 = fixNumber('abc')
+// ^? NaN
+
+const value3 = fixNumber('abc', 0)
+// ^? 0
+```
+
## Contributing
Contributions are welcome! Please submit a pull request or open an issue to discuss any proposed changes or feature requests.
diff --git a/biome.json b/biome.json
new file mode 100644
index 0000000..07838f2
--- /dev/null
+++ b/biome.json
@@ -0,0 +1,37 @@
+{
+ "$schema": "https://biomejs.dev/schemas/1.4.1/schema.json",
+ "files": {
+ "ignore": [
+ "node_modules",
+ "coverage"
+ ]
+ },
+ "organizeImports": {
+ "enabled": true
+ },
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "all": true
+ }
+ },
+ "formatter": {
+ "enabled": true,
+ "formatWithErrors": false,
+ "ignore": [],
+ "indentStyle": "space",
+ "indentWidth": 2,
+ "lineWidth": 120
+ },
+ "javascript": {
+ "formatter": {
+ "enabled": true,
+ "quoteStyle": "single",
+ "jsxQuoteStyle": "double",
+ "trailingComma": "all",
+ "semicolons": "asNeeded",
+ "arrowParentheses": "always",
+ "quoteProperties": "asNeeded"
+ }
+ }
+}
diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs
new file mode 100644
index 0000000..7e813f8
--- /dev/null
+++ b/docs/astro.config.mjs
@@ -0,0 +1,44 @@
+// eslint-disable-next-line import/extensions
+import { defineConfig } from 'astro/config'
+import starlight from '@astrojs/starlight'
+
+export default defineConfig({
+ integrations: [
+ starlight({
+ title: 'type-assurer',
+ social: {
+ github: 'https://github.com/hacomono-lib/type-assurer',
+ },
+ sidebar: [
+ {
+ label: 'Home',
+ link: '/',
+ },
+ {
+ label: 'Introduction',
+ collapsed: false,
+ items: [
+ { label: 'Getting Started', link: '/guides/start' },
+ { label: 'Concepts', link: '/guides/concepts' },
+ ],
+ },
+ {
+ label: 'Reference',
+ collapsed: false,
+ items: [
+ {
+ label: 'Common',
+ collapsed: false,
+ autogenerate: { directory: '/reference/common', collapsed: false },
+ },
+ {
+ label: 'Type Guards',
+ collapsed: false,
+ autogenerate: { directory: '/reference/typeGuards', collapsed: false },
+ },
+ ],
+ },
+ ],
+ }),
+ ],
+})
diff --git a/docs/public/favicon.svg b/docs/public/favicon.svg
new file mode 100644
index 0000000..cba5ac1
--- /dev/null
+++ b/docs/public/favicon.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/docs/src/assets/houston.webp b/docs/src/assets/houston.webp
new file mode 100644
index 0000000..930c164
Binary files /dev/null and b/docs/src/assets/houston.webp differ
diff --git a/docs/src/content/config.ts b/docs/src/content/config.ts
new file mode 100644
index 0000000..4624b9a
--- /dev/null
+++ b/docs/src/content/config.ts
@@ -0,0 +1,7 @@
+import { defineCollection } from 'astro:content'
+import { docsSchema, i18nSchema } from '@astrojs/starlight/schema'
+
+export const collections = {
+ docs: defineCollection({ schema: docsSchema() }),
+ i18n: defineCollection({ type: 'data', schema: i18nSchema() }),
+}
diff --git a/docs/src/content/docs/guides/concepts.md b/docs/src/content/docs/guides/concepts.md
new file mode 100644
index 0000000..d3b2a7a
--- /dev/null
+++ b/docs/src/content/docs/guides/concepts.md
@@ -0,0 +1,4 @@
+---
+title: Concept
+description: type-assurer library concept
+---
diff --git a/docs/src/content/docs/guides/start.md b/docs/src/content/docs/guides/start.md
new file mode 100644
index 0000000..089ec5e
--- /dev/null
+++ b/docs/src/content/docs/guides/start.md
@@ -0,0 +1,4 @@
+---
+title: Getting Started
+description: Getting started with type-assurer library
+---
diff --git a/docs/src/content/docs/index.mdx b/docs/src/content/docs/index.mdx
new file mode 100644
index 0000000..f53a85b
--- /dev/null
+++ b/docs/src/content/docs/index.mdx
@@ -0,0 +1,37 @@
+---
+title: type-assurer
+description: A type guard / type assertion for TypeScript
+template: splash
+hero:
+ tagline: A type guard / type assertion for TypeScript
+ actions:
+ - text: Getting Started
+ link: /guides/start/
+ icon: right-arrow
+ variant: primary
+ - text: Repository
+ link: https://github.com/hacomono-lib/type-assurer
+ icon: github
+---
+
+import { Card, CardGrid } from '@astrojs/starlight/components';
+
+## Concepts
+
+
+
+ TypeScript first implementation with accurate type inference.
+
+
+
+ ES Modules and TypeScript allow for tree-shaking, so you can optimize your bundle size.
+
+
+
+ No external dependencies, so you don't have to worry about security vulnerabilities.
+
+
+
+ 7 types of guard, 2 types of assertion utilities are provided.
+
+
diff --git a/docs/src/content/docs/reference/common/TypeAssertionError.md b/docs/src/content/docs/reference/common/TypeAssertionError.md
new file mode 100644
index 0000000..7f01006
--- /dev/null
+++ b/docs/src/content/docs/reference/common/TypeAssertionError.md
@@ -0,0 +1,6 @@
+---
+title: TypeAssertionError
+description: TypeAssertionError is an error that occurs when a type assertion fails.
+---
+
+test
diff --git a/docs/src/content/docs/reference/typeGuards/date.md b/docs/src/content/docs/reference/typeGuards/date.md
new file mode 100644
index 0000000..f323382
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/date.md
@@ -0,0 +1,3 @@
+===
+title: Date
+---
diff --git a/docs/src/content/docs/reference/typeGuards/empty.md b/docs/src/content/docs/reference/typeGuards/empty.md
new file mode 100644
index 0000000..133b9fa
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/empty.md
@@ -0,0 +1,3 @@
+---
+title: empty
+---
diff --git a/docs/src/content/docs/reference/typeGuards/function.md b/docs/src/content/docs/reference/typeGuards/function.md
new file mode 100644
index 0000000..3951f69
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/function.md
@@ -0,0 +1,151 @@
+---
+title: function
+description: A Type Guard Utility functions for checking if a value is a function.
+---
+A Type Guard Utility functions for checking if a value is a function.
+
+## Example of return value
+
+| input | result |
+| ----- | ------ |
+| function
(e.g. `() => {}`) | true |
+| function object
(e.g. `new Function()`) | true |
+| async function
(e.g. `async () => {}`) | true |
+| async function object
(e.g. `new Function()`) | true |
+| generator function
(e.g. `function* () {}`) | true |
+| generator function object
(e.g. `new Function()`) | true |
+| async generator function
(e.g. `async function* () {}`) | true |
+| async generator function object
(e.g. `new Function()`) | true |
+| constructor
(e.g. `class Foo {}`) | true |
+| other
(e.g. `'foo'`, `null`, `undefined`, `{}`, `[]`) | false |
+
+## isFunction
+
+A Type Guard function for checking if a value is a function.
+
+This function is determined by `typeof target === 'function'`.
+
+### Basic Usage
+
+```typescript
+function isFunction(target: unknown): target is Function
+```
+
+#### params
+
+- `target` .. The value to check.
+
+#### returns
+
+- `true` .. When the value is a function.
+- `false` .. When the value is not a function.
+
+### Examples
+
+```typescript
+import { isFunction } from 'type-assurer'
+
+const value: unknown = () => {}
+
+if (isFunction(value)) {
+ // value is function
+} else {
+ // value is unknown
+}
+```
+
+## assertFunction
+
+A Type Assertion function for checking if a value is a function.
+
+### Basic Usage
+
+```typescript
+function assertFunction(target: unknown, message?: ErrorMessage): asserts target is Function
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. (optional) The error message to be thrown when the value is not a function.
+
+#### returns
+
+- `void` .. When the value is a function.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a function.
+
+### Examples
+
+```typescript
+import { assertFunction } from 'type-assurer'
+
+const value: unknown = () => {}
+
+assertFunction(value)
+// When the value is not a function, TypeAssertionError is thrown.
+// value is function
+```
+
+## ensureFunction
+
+Ensure that the value is a function.
+
+### Basic Usage
+
+```typescript
+function ensureFunction(target: unknown, message?: ErrorMessage): Function
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. (optional) The error message to be thrown when the value is not a function.
+
+#### returns
+
+- `Function` .. When the value is a function.
+
+### Examples
+
+```typescript
+import { ensureFunction } from 'type-assurer'
+
+function getFunction() { return () => {} }
+
+const result = ensureFunction(getFunction())
+// When the value is not a function, TypeAssertionError is thrown.
+// result is function
+```
+
+## fallbackFunction
+
+Fallback to the fallback function if the value is not a function.
+
+### Basic Usage
+
+```typescript
+function fallbackFunction(target: unknown, fallback: Function): Function
+```
+
+#### params
+
+- `target` .. The value to check.
+- `fallback` .. The fallback function.
+
+#### returns
+
+- `Function` .. When the value is a function.
+
+### Examples
+
+```typescript
+import { fallbackFunction } from 'type-assurer'
+
+function getFunction() { return () => 'foo' }
+
+const result = fallbackFunction(getFunction(), () => 'bar')
+// result is function
+```
diff --git a/docs/src/content/docs/reference/typeGuards/json-parsable.md b/docs/src/content/docs/reference/typeGuards/json-parsable.md
new file mode 100644
index 0000000..e26900c
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/json-parsable.md
@@ -0,0 +1,241 @@
+---
+title: JSON-parsable
+description: Type Guards and Type Assertions for JSON-parsable.
+---
+
+A Type Guard and Type Assertion functions for checking if a value is a JSON-parsable.
+
+"JSON-parsable" means that the value is a JSON or JSON parsable string using `JSON.parse()`.
+
+## Example of return value
+
+| input | example input | result | parsed result |
+| ----- | -------------- | ------ | ------------- |
+| number string | `'0'` | true | `0` |
+| ^ | `'0123'` | true | `123` |
+| ^ | `'1.1'` | true | `1.1` |
+| ^ | `'Infinity'` | false | no result |
+| boolean string | `'true'` | true | `true` |
+| ^ | `'false'` | true | `false` |
+| null string | `'null'` | true | `null` |
+| json-object string | `'{}'` | true | `{}` |
+| ^ | `'{"foo":"bar"}'` | true | `{ foo: 'bar' }` |
+| ^ | `'{"foo":undefined}'` | false | no result |
+| ^ | `'{"foo":() => 'bar'}'` | false | no result |
+| ^ | `'[1, 2, 3]'` | true | `[1, 2, 3]` |
+
+## isJSONParsable
+
+A Type Guard function for checking if a value is a JSON-parsable.
+
+### Basic Usage
+
+```typescript
+function isJSONParsable(target: unknown): target is JSONParsable
+```
+
+#### params
+
+- `target` .. The value to check.
+
+#### returns
+
+- `true` .. When the value is a JSON-parsable.
+- `false` .. When the value is not a JSON-parsable.
+
+### Examples
+
+```typescript
+import { isJSONParsable } from 'type-assurer'
+
+const value = '{"foo":"bar"}'
+if (isJSONParsable(value)) {
+ // this is true, value is JSONParsable
+}
+```
+
+## assertJSONParsable
+
+A Type Assertion function for checking if a value is a JSON-parsable.
+
+### Basic Usage
+
+```typescript
+function assertJSONParsable(target: unknown, message?: ErrorMessage): asserts target is JSONParsable
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. The error message to throw when the value is not a JSON-parsable.
+
+#### returns
+
+- `void` .. When the value is a JSON-parsable.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a JSON-parsable.
+
+### Examples
+
+```typescript
+import { assertJSONParsable } from 'type-assurer'
+
+const value = '{"foo":"bar"}'
+assertJSONParsable(value)
+// When the value is not a JSON-parsable, TypeAssertionError is thrown.
+// value is JSONParsable
+```
+
+## ensureJSONParsable
+
+Ensure that the value is a JSON-parsable.
+
+### Basic Usage
+
+```typescript
+function ensureJSONParsable(target: unknown, message?: ErrorMessage): JSONParsable
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. The error message to throw when the value is not a JSON-parsable.
+
+#### returns
+
+- `JSONParsable` .. When the value is a JSON-parsable.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a JSON-parsable.
+
+### Examples
+
+```typescript
+import { ensureJSONParsable } from 'type-assurer'
+
+function getValue() { return '{"foo":"bar"}' }
+
+const value = ensureJSONParsable(getValue())
+// When the value is not a JSON-parsable, TypeAssertionError is thrown.
+// value is JSONParsable
+```
+
+## fallbackJSONParsable
+
+Fallback to the default value if the value is not a JSON-parsable.
+
+### Basic Usage
+
+```typescript
+function fallbackJSONParsable(target: unknown, fallback: JSONParsable): JSONParsable
+```
+
+#### params
+
+- `target` .. The value to check.
+- `fallback` .. The default value to return if the value is not a JSON-parsable.
+
+#### returns
+
+- `JSONParsable` .. When the value is a JSON-parsable. Otherwise, the fallback value.
+
+### Examples
+
+```typescript
+import { fallbackJSONParsable } from 'type-assurer'
+
+function getValue() { return '{"foo":"bar"}' }
+
+const value = fallbackJSONParsable(getValue(), { baz: 'qux' })
+// When the value is not a JSON-parsable, value is { baz: 'qux' }
+```
+
+## coerceJSON
+
+Coerce the value to a JSON if it is a JSON like object or JSON parsable string.
+Otherwise, throw an error.
+
+If the value is a string, check with `isJSONParsable` and return the result of `JSON.parse`.
+If the value is not a string, check with `isJSON` and return the same value if it is true.
+
+### Basic Usage
+
+```typescript
+function coerceJSON(target: unknown, message?: ErrorMessage): JSON
+```
+
+#### params
+
+- `target` .. The value to coerce to a JSON.
+- `message` .. The error message to throw when the value is not a JSON.
+
+#### returns
+
+- `JSON` .. When the value is a JSON.
+
+#### throws
+
+- `TypeAssertionError` .. When the value cannot be coerced to a JSON.
+
+### Examples
+
+```typescript
+import { coerceJSON } from 'type-assurer'
+
+function getValue() { return '{"foo":"bar"}' }
+
+const value = coerceJSON(getValue())
+// value is { foo: 'bar' }
+
+function getValue2() { return { foo: 'bar' } }
+
+const value2 = coerceJSON(getValue2())
+// value2 is { foo: 'bar' }
+```
+
+## fixJSON
+
+Fix the value to a JSON if it is a JSON like object or JSON parsable string.
+Otherwise, return the default value.
+
+If the value is a string, check with `isJSONParsable` and return the result of `JSON.parse`.
+If the value is not a string, check with `isJSON` and return the same value if it is true.
+
+### Basic Usage
+
+```typescript
+function fixJSON(target: unknown, fallback: JSON): JSON
+```
+
+#### params
+
+- `target` .. The value to fix to a JSON.
+- `fallback` .. The default value to return if the value is not a JSON.
+
+#### returns
+
+- `JSON` .. When the value is a JSON. Otherwise, the fallback value.
+
+### Examples
+
+```typescript
+import { fixJSON } from 'type-assurer'
+
+function getValue() { return '{"foo":"bar"}' }
+
+const value = fixJSON(getValue(), {})
+// value is { foo: 'bar' }
+
+function getValue2() { return { foo: 'bar' } }
+
+const value2 = fixJSON(getValue2(), {})
+// value2 is { foo: 'bar' }
+
+function getValue3() { return 'foo' }
+
+const value3 = fixJSON(getValue3(), {})
+// value3 is {}
+```
diff --git a/docs/src/content/docs/reference/typeGuards/json.md b/docs/src/content/docs/reference/typeGuards/json.md
new file mode 100644
index 0000000..0a0fa48
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/json.md
@@ -0,0 +1,265 @@
+---
+title: JSON
+description: A Type Guard Utility functions for checking if a value is JSON like
+---
+A Type Guard Utility functions for checking if a value is JSON like.
+
+"JSON like" means a value that can be converted to a JSON object string using `JSON.stringify` without missing object members, or a value that can be converted to a JSON primitive value.
+
+:::note
+If the value is an object, it checks whether the result of `JSON.parse(JSON.stringify(value))` is exactly the same as the original object.
+
+If the object has a method, it will not be included in the result of `JSON.stringify`, so it will not match exactly.
+
+However, [WellKnown Symbols](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbol) are not included in the result of JSON.stringify and are not referenced, so they are not included in this check.
+
+Also, if there is a [toJSON](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#tojson_%E3%81%AE%E6%8C%99%E5%8B%95) method at the root, it checks the result of that method.
+
+e.g.
+
+```typescript
+const sample1 = {
+ foo: 'bar',
+}
+// this is true
+
+const sample2 = {
+ foo: 'bar',
+ // methods are not included in the result of JSON.stringify,
+ // so returns false
+ baz() { return 'qux' }
+}
+// this is false
+
+const sample3 = {
+ foo: 'bar',
+ // if there is a toJSON method at the root,
+ // it checks the result of that method
+ toJSON() { return 'baz' }
+}
+// this is true
+
+const sample4 = {
+ foo: 'bar',
+ // WellKnown Symbols are not included in the result of JSON.stringify
+ // and are not referenced, so they are not included in this check
+ [Symbol.toPrimitive]() { return 'baz' },
+}
+// this is true
+```
+
+:::
+
+## Example of return value
+
+| input | example input | result |
+| ----- | -------------- | ------ |
+| boolean | `true` | true |
+| ^ | `false` | true |
+| number | `0` | true |
+| ^ | `1` | true |
+| ^ | `1.1` | true |
+| not-finite number | `Infinity` | false |
+| ^ | `-Infinity` | false |
+| ^ | `NaN` | false |
+| string | `'foo'` | false |
+| null | `null` | true |
+| undefined | `undefined` | false |
+| symbol | `Symbol('foo')` | false |
+| bigint | `0n` | false |
+| object | `{}` | true |
+| ^ | `{ foo: 'bar' }` | true |
+| ^ | `{ foo: undefined }` | false |
+| ^ | `{ foo: () => 'bar' }` | false |
+| object with `valueOf` | `{ valueOf: () => ({ foo: 'bar' }) }` | true |
+| object with `toJSON` | `{ toJSON: () => 'bar' }` | true |
+| object with `[Symbol.toPrimitive]` | `{ [Symbol.toPrimitive]: () => true }` | true |
+| array | `[]` | true |
+| ^ | `[1, 2, 3]` | true |
+| Date | `new Date()` | true |
+
+## isJSON
+
+A Type Guard function for checking if a value is a JSON like.
+
+### Basic Usage
+
+```typescript
+function isJSON(target: unknown): target is JSON
+```
+
+#### params
+
+- `target` .. The value to check.
+
+#### returns
+
+- `true` .. When the value is a JSON.
+- `false` .. When the value is not a JSON.
+
+### Examples
+
+```typescript
+import { isJSON } from 'type-assurer'
+
+const value = { foo: 'bar' }
+
+if (isJSON(value)) {
+ // value is { foo: string }
+} else {
+ // value is never
+}
+
+const value2 = { foo: () => 'bar' }
+
+if (isJSON(value2)) {
+ // value2 is never
+} else {
+ // value2 is { foo: () => string }
+}
+
+const value3 = { foo: 'bar' } as unknown
+
+if (isJSON(value3)) {
+ // value3 is JSON
+} else {
+ // value3 is unknown
+}
+```
+
+## assertJSON
+
+A Type Assertion function for checking if a value is a JSON.
+
+### Basic Usage
+
+```typescript
+function assertJSON(target: unknown, message?: TypeErrorMessage): asserts target is JSON
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. (optional) The error message to be displayed when the assertion fails.
+
+#### returns
+
+- `void` .. When the value is a JSON.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a JSON.
+
+### Examples
+
+```typescript
+import { assertJSON } from 'type-assurer'
+
+const value = { foo: 'bar' }
+
+assertJSON(value)
+// When the value is not a JSON, TypeAssertionError is thrown.
+// value is { foo: string }
+
+const value2 = { foo: () => 'bar' }
+
+assertJSON(value2)
+// When the value is not a JSON, TypeAssertionError is thrown.
+// value2 is never
+
+const value3 = { foo: 'bar' } as unknown
+
+assertJSON(value3)
+// When the value is not a JSON, TypeAssertionError is thrown.
+// value3 is JSON
+```
+
+### ensureJSON
+
+Ensures that the value is a JSON. If it is not a JSON, an error is thrown.
+
+### Basic Usage
+
+```typescript
+function ensureJSON(target: unknown, message?: TypeErrorMessage): JSON
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. (optional) The error message to be displayed when the assertion fails.
+
+#### returns
+
+- `JSON` .. When the value is a JSON.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a JSON.
+
+### Examples
+
+```typescript
+import { ensureJSON } from 'type-assurer'
+
+function getValue() { return { foo: 'bar' } }
+
+const value = ensureJSON(getValue())
+// When the value is not a JSON, TypeAssertionError is thrown.
+// value is { foo: string }
+
+function getValue2() { return { foo: () => 'bar' } }
+
+const value2 = ensureJSON(getValue2())
+// When the value is not a JSON, TypeAssertionError is thrown.
+// value2 is never
+
+function getValue3() { return { foo: 'bar' } as unknown }
+
+const value3 = ensureJSON(getValue3())
+// When the value is not a JSON, TypeAssertionError is thrown.
+// value3 is JSON
+```
+
+## fallbackJSON
+
+Fallback to the default value if the value is not a JSON.
+
+### Basic Usage
+
+```typescript
+function fallbackJSON(target: unknown, fallback: JSON): Jsonifiable
+```
+
+#### params
+
+- `target` .. The value to check.
+- `fallback` .. The default value to return if the value is not a JSON.
+
+#### returns
+
+- `JSON` .. When the value is a JSON. Otherwise, the fallback value.
+
+### Examples
+
+```typescript
+import { fallbackJSON } from 'type-assurer'
+
+function getValue() { return { foo: 'bar' } }
+
+const value = fallbackJSON(getValue(), { baz: 'qux' })
+// When the value is not a JSON, the process continues.
+// value is { foo: string } | { baz: string }
+
+function getValue2() { return { foo: () => 'bar' } }
+
+const value2 = fallbackJSON(getValue2(), { baz: 'qux' })
+// When the value is not a JSON, the process continues.
+// value2 is { baz: string }
+
+function getValue3() { return { foo: 'bar' } as unknown }
+
+const value3 = fallbackJSON(getValue3(), { baz: 'qux' })
+// When the value is not a JSON, the process continues.
+// vlaue3 is JSON | { baz: string }
+```
diff --git a/docs/src/content/docs/reference/typeGuards/nil.md b/docs/src/content/docs/reference/typeGuards/nil.md
new file mode 100644
index 0000000..87f43c6
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/nil.md
@@ -0,0 +1,52 @@
+---
+title: nil
+description: A Type Guard Utility functions for checking if a value is `null` or `undefined`.
+---
+A Type Guard Utility functions for checking if a value is `null` or `undefined`.
+
+:::note
+`assertNil` `ensureNil` `fallbackNil` are not implemented because it is not necessary. they are not useful.
+:::
+
+## Example of return value
+
+| input | result |
+| ----- | ------ |
+| `null` | true |
+| `undefined` | true |
+| other | false |
+
+## isNil
+
+A Type Guard function for checking if a value is `null` or `undefined`.
+
+This function is determined by `target === null || target === undefined`.
+
+### Basic Usage
+
+```typescript
+function isNil(target: T): target is Exclude
+```
+
+#### params
+
+- `target` .. The value to check.
+
+#### returns
+
+- `true` .. When the value is `null` or `undefined`.
+- `false` .. When the value is not `null` and not `undefined`.
+
+### Examples
+
+```typescript
+import { isNil } from 'type-assurer'
+
+const value: unknown = 0
+
+if (isNil(value)) {
+ // value is null or undefined
+} else {
+ // value is number
+}
+```
diff --git a/docs/src/content/docs/reference/typeGuards/not-empty.md b/docs/src/content/docs/reference/typeGuards/not-empty.md
new file mode 100644
index 0000000..a44f2ba
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/not-empty.md
@@ -0,0 +1,3 @@
+---
+title: not-empty
+---
diff --git a/docs/src/content/docs/reference/typeGuards/not-nil.md b/docs/src/content/docs/reference/typeGuards/not-nil.md
new file mode 100644
index 0000000..778ecf5
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/not-nil.md
@@ -0,0 +1,122 @@
+---
+title: not-nil
+description: A Type Guard Utility functions for checking if a value is not `null` and not `undefined`.
+---
+A Type Guard Utility functions for checking if a value is not `null` and not `undefined`.
+
+:::note
+`fallbackNotNil` is not implemented because it is not necessary. use `??` operator instead.
+:::
+
+## Example of return value
+
+| input | result |
+| ----- | ------ |
+| `null` | false |
+| `undefined` | false |
+| other | true |
+
+## isNotNil
+
+A Type Guard function for checking if a value is not `null` and not `undefined`.
+
+This function is determined by `target !== null && target !== undefined`.
+
+### Basic Usage
+
+```typescript
+function isNotNil(target: T): target is Exclude
+```
+
+#### params
+
+- `target` .. The value to check.
+
+#### returns
+
+- `true` .. When the value is not `null` and not `undefined`.
+- `false` .. When the value is `null` or `undefined`.
+
+### Examples
+
+```typescript
+import { isNotNil } from 'type-assurer'
+
+const value: unknown = 0
+
+if (isNotNil(value)) {
+ // value is number
+} else {
+ // value is null or undefined
+}
+```
+
+## assertNotNil
+
+A Type Assertion function for checking if a value is not `null` and not `undefined`.
+
+### Basic Usage
+
+```typescript
+function assertNotNil(target: T): asserts target is Exclude
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. (optional) The error message to be thrown when the value is `null` or `undefined`.
+
+#### returns
+
+- `void` .. When the value is not `null` and not `undefined`.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is `null` or `undefined`.
+
+### Examples
+
+```typescript
+import { assertNotNil } from 'type-assurer'
+
+const value: unknown = 0
+
+assertNotNil(value)
+// When value is not null and not undefined, this function does not throw an error.
+// value is {}
+```
+
+## ensureNotNil
+
+Ensure that the value is not `null` and not `undefined`.
+
+### Basic Usage
+
+```typescript
+function ensureNotNil(target: T, message?: ErrorMessage): Exclude
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. (optional) The error message to be thrown when the value is `null` or `undefined`.
+
+#### returns
+
+- `Exclude` .. When the value is not `null` and not `undefined`.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is `null` or `undefined`.
+
+### Examples
+
+```typescript
+import { ensureNotNil } from 'type-assurer'
+
+function getValue(): number | null { return null }
+
+const value = ensureNotNil(getValue())
+// When value is not null and not undefined, this function does not throw an error.
+// value is number
+```
diff --git a/docs/src/content/docs/reference/typeGuards/number-parsable.md b/docs/src/content/docs/reference/typeGuards/number-parsable.md
new file mode 100644
index 0000000..9041beb
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/number-parsable.md
@@ -0,0 +1,280 @@
+---
+title: number-parsable
+describe: A Type Guard Utility functions for checking if a value is a NumberParsable.
+---
+A Type Guard Utility functions for checking if a value is a NumberParsable.
+
+"NumberParsable" is a value that can be converted to a number, using `Number(value)`.
+
+## Example of return value
+
+| input | example input | result | parsed result |
+| ----- | -------------- | ------ | ------------- |
+| number | `0` | true | `0` |
+| ^ | `1` | true | `1` |
+| ^ | `1.1` | true | `1.1` |
+| ^ | `Infinity` | true | `Infinity` |
+| ^ | `-Infinity` | true | `-Infinity` |
+| NaN | `NaN` | false | no result |
+| number object | `new Number(1)` | true | `1` |
+| boolean | `true` | true | `1` |
+| ^ | `false` | true | `0` |
+| boolean object | `new Boolean(true)` | true | same as input of `Boolean` constructor argument |
+| null | `null` | true | `0` |
+| undefined | `undefined` | false | no result |
+| string number | `'0'` | true | `0` |
+| ^ | `'0123'` | true | `123` |
+| ^ | `'1.1'` | true | `1.1` |
+| ^ | `'Infinity'` | true | `Infinity` |
+| string bigint | `'0n'` | false | no result |
+| string | `'foo'` | false | no result |
+| object with 'valueOf' | `new Number(1)` | true | `1` |
+| ^ | `{ valueOf: () => 1 }` | true | `1` |
+| ^ | `{ valueOf: () => true }` | true | `1` |
+| ^ | `{ valueOf: () => 'foo' }` | false | no result |
+| object with '[Symbol.toPrimitive]' | `{ [Symbol.toPrimitive]: () => 1 }` | true | `1` |
+| ^ | `{ [Symbol.toPrimitive]: () => true }` | true | `1` |
+| ^ | `{ [Symbol.toPrimitive]: () => 'foo' }` | false | no result |
+| other | `''`, `false`, `true`, `null`, `undefined` | false | no result |
+
+:::note
+Returns false for cases where `Number(value)` would cause an error, such as Symbol.
+:::
+
+## isNumberParsable
+
+A Type Guard function for checking if a value is a NumberParsable.
+
+### Basic Usage
+
+```typescript
+function isNumberParsable(target: unknown): target is NumberParsable
+```
+
+#### params
+
+- `target` .. The value to check.
+
+#### returns
+
+- `true` .. When the value is a NumberParsable.
+- `false` .. When the value is not a NumberParsable.
+
+### Examples
+
+```typescript
+import { isNumberParsable } from 'type-assurer'
+
+const value: unknown = '123'
+
+if (isNumberParsable(value)) {
+ // value is NumberParsable
+} else {
+ // value is unknown
+}
+
+const value2 = '123' as '123' | 'foo'
+
+if (isNumberParsable(value2)) {
+ // value2 is '123'
+} else {
+ // value2 is 'foo'
+}
+```
+
+## assertNumberParsable
+
+A Type Assertion function for checking if a value is a NumberParsable.
+
+### Basic Usage
+
+```typescript
+function assertNumberParsable(target: unknown, message?: ErrorMessage): asserts target is NumberParsable
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. (optional) The error message to be displayed when the assertion fails.
+
+#### returns
+
+- `void` .. When the value is a NumberParsable.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a NumberParsable.
+
+### Examples
+
+```typescript
+import { assertNumberParsable } from 'type-assurer'
+
+const value: unknown = '123'
+
+assertNumberParsable(value)
+// When the value is NumberParsable, the process continues.
+// value is NumberParsable
+
+const value2 = '123' as '123' | 'foo'
+
+assertNumberParsable(value2)
+// When the value is NumberParsable, the process continues.
+// value2 is '123'
+```
+
+## ensureNumberParsable
+
+Ensures that the value is a NumberParsable. If not, throw an error.
+
+### Basic Usage
+
+```typescript
+function ensureNumberParsable(target: unknown, message?: ErrorMessage): NumberParsable
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. (optional) The error message to be displayed when the assertion fails.
+
+#### returns
+
+- `NumberParsable` .. When the value is a NumberParsable.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a NumberParsable.
+
+### Examples
+
+```typescript
+import { ensureNumberParsable } from 'type-assurer'
+
+function getValue(): unknown { return '123' }
+
+const value = ensureNumberParsable(getValue())
+// When the value is NumberParsable, the process continues.
+// value is NumberParsable
+
+function getValue2(): '123' | 'foo' { return '123' }
+
+const value2 = ensureNumberParsable(getValue2())
+// When the value is NumberParsable, the process continues.
+// value2 is '123'
+```
+
+## fallbackNumberParsable
+
+Fallback to the default value if the value is not a NumberParsable.
+
+### Basic Usage
+
+```typescript
+function fallbackNumberParsable(target: unknown, fallbackValue: NumberParsable): NumberParsable
+```
+
+#### params
+
+- `target` .. The value to check.
+- `fallbackValue` .. The default value to be returned when the value is not a NumberParsable.
+
+#### returns
+
+- `NumberParsable` .. When the value is a NumberParsable. Otherwise, the fallback value.
+
+### Examples
+
+```typescript
+import { fallbackNumberParsable } from 'type-assurer'
+
+function getValue(): unknown { return '123' }
+
+const value = fallbackNumberParsable(getValue(), 0)
+// When the value is NumberParsable, the process continues.
+// value is NumberParsable
+
+function getValue2(): '123' | 'foo' { return '123' }
+
+const value2 = fallbackNumberParsable(getValue2(), 0)
+// When the value is NumberParsable, the process continues.
+// value2 is '123' | 0
+```
+
+## coerceNumber
+
+Parse the value as a number. If it fails, throw an error.
+
+### Basic Usage
+
+```typescript
+function coerceNumber(target: unknown, message?: ErrorMessage): number
+```
+
+#### params
+
+- `target` .. The value to parse.
+- `message` .. (optional) The error message to be displayed when the parsing fails.
+
+#### returns
+
+- `number` .. When the value is a NumberParsable.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a NumberParsable.
+
+### Examples
+
+```typescript
+import { coerceNumber } from 'type-assurer'
+
+function getValue(): unknown { return '123' }
+
+const value = coerceNumber(getValue())
+// When the value is NumberParsable, the process continues.
+// value is number
+
+function getValue2(): '123' | 456 | 'foo' | 'bar' { return '123' }
+
+const value2 = coerceNumber(getValue2())
+// When the value is NumberParsable, the process continues.
+// value2 is 123 | 456
+```
+
+## fixNumber
+
+Parse the value as a number. If it fails, return the fallback value.
+
+### Basic Usage
+
+```typescript
+function fixNumber(target: unknown, fallbackValue: number): number
+```
+
+#### params
+
+- `target` .. The value to parse.
+- `fallbackValue` .. The default value to be returned when the parsing fails.
+
+#### returns
+
+- `number` .. When the value is a NumberParsable. Otherwise, the fallback value.
+
+### Examples
+
+```typescript
+import { fixNumber } from 'type-assurer'
+
+function getValue(): unknown { return '123' }
+
+const value = fixNumber(getValue(), 0)
+// When the value is NumberParsable, the process continues.
+// value is number
+
+function getValue2(): '123' | 456 | 'foo' | 'bar' { return '123' }
+
+const value2 = fixNumber(getValue2(), 789)
+// When the value is NumberParsable, the process continues.
+// value2 is 123 | 456 | 789
+```
diff --git a/docs/src/content/docs/reference/typeGuards/number.md b/docs/src/content/docs/reference/typeGuards/number.md
new file mode 100644
index 0000000..8c1949a
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/number.md
@@ -0,0 +1,158 @@
+---
+title: number
+description: A Type Guard Utility functions for checking if a value is a number.
+---
+A Type Guard Utility functions for checking if a value is a number.
+
+:::note
+`NaN` is a type of number, but it is judged as false because it is not a number.
+:::
+
+## Example of return value
+
+| input | result |
+| ----- | ------ |
+| number
(e.g. `0`) | true |
+| Non-finite number without `NaN`
(e.g. `Infinity`, `-Infinity`) | true |
+| NaN | false |
+| number object
(e.g. `new Number()`) | false |
+| BigInt
(e.g. `0n`) | false |
+| object including `Symbol.toPrimitive`
(e.g. `{ [Symbol.toPrimitive]: () => 0 }`) | false |
+| object including `valueOf`
(e.g. `{ valueOf: () => 0 }`) | false |
+| other
(e.g. `'foo'`, `null`, `undefined`, `{}`, `[]`) | false |
+
+## isNumber
+
+A Type Guard function for checking if a value is a number.
+
+This function is determined by `typeof target === 'number' && !isNaN(target)`.
+
+### Basic Usage
+
+```typescript
+function isNumber(target: unknown): target is number
+```
+
+#### params
+
+- `target` .. The value to check.
+
+#### returns
+
+- `true` .. When the value is a number.
+- `false` .. When the value is not a number. (including `NaN`)
+
+### Examples
+
+```typescript
+import { isNumber } from 'type-assurer'
+
+const value: unknown = 0
+
+if (isNumber(value)) {
+ // value is number
+} else {
+ // value is unknown
+}
+```
+
+## assertNumber
+
+A Type Assertion function for checking if a value is a number.
+
+### Basic Usage
+
+```typescript
+function assertNumber(target: unknown, message?: ErrorMessage): asserts target is number
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. (optional) The error message to be thrown when the value is not a number.
+
+#### returns
+
+- `void` .. When the value is a number.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a number.
+
+### Examples
+
+```typescript
+import { assertNumber } from 'type-assurer'
+
+const value: unknown = 0
+
+assertNumber(value)
+// When the value is not a number, TypeAssertionError is thrown.
+// value is number
+```
+
+## ensureNumber
+
+Ensure that the value is a number. If it is not a number, it will be converted to a number.
+
+### Basic Usage
+
+```typescript
+function ensureNumber(target: unknown, message?: ErrorMessage): number
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. (optional) The error message to be thrown when the value is not a number.
+
+#### returns
+
+- `number` .. When the value is a number.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a number.
+
+### Examples
+
+```typescript
+import { ensureNumber } from 'type-assurer'
+
+function getValue(): unknown { return '0' }
+
+const value: number = ensureNumber(getValue())
+// When the value is not a number, TypeAssertionError is thrown.
+// value is number
+```
+
+## fallbackNumber
+
+Fallback to the default value if the value is not a number.
+
+### Basic Usage
+
+```typescript
+function fallbackNumber(target: unknown, fallbackValue: number): number
+```
+
+#### params
+
+- `target` .. The value to check.
+- `fallbackValue` .. The default value to be returned when the value is not a number.
+
+#### returns
+
+- `number` .. When the value is a number. If the value is not a number, the default value is returned.
+
+### Examples
+
+```typescript
+import { fallbackNumber } from 'type-assurer'
+
+function getValue(): unknown { return '0' }
+
+const value: number = fallbackNumber(getValue(), 1)
+// When the value is not a number, 1 is returned.
+// value is number
+```
diff --git a/docs/src/content/docs/reference/typeGuards/object.md b/docs/src/content/docs/reference/typeGuards/object.md
new file mode 100644
index 0000000..30cfd4d
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/object.md
@@ -0,0 +1,228 @@
+---
+title: object
+description: A Type Guard Utility functions for checking if a value is an Object.
+---
+A Type Guard Utility functions for checking if a value is an Object.
+
+## Example of return value
+
+| input | result |
+| ----- | ------ |
+| Object
(e.g. `{ foo: 'bar' }`) | true |
+| Array
(e.g. `['foo', 'bar']`) | false |
+| Function
(e.g. `() => {}`) | false |
+| null | false |
+| undefined | false |
+| other
(e.g. `0`, `''`, `false`, `true`) | false |
+
+## Example of return types
+
+| input | result |
+| ----- | ------ |
+| `object` | `object` |
+| `unknown` | `Record` |
+| some type that satisfies `Record` | same type |
+| some instance | same type |
+| some class instance | same type |
+| other | `never` |
+
+## isObject
+
+A Type Guard function for checking if a value is an Object.
+
+This determination is made by `target !== null && !Array.isArray(target) && typeof target === 'object'`.
+
+### Basic Usage
+
+```typescript
+function isObject(target: unknown): target is object
+```
+
+#### params
+
+- `target` .. The value to check.
+
+#### returns
+
+- `true` .. When the value is an Object.
+- `false` .. When the value is not an Object.
+
+'Object' here means a value that is not null, not an Array, and has a type of 'object'.
+
+### Example
+
+
+```typescript
+import { isObject } from 'type-assurer'
+
+const value: unknown = { foo: 'bar' }
+
+if (isObject(value)) {
+ // value is Record
+} else {
+ // value is unknown
+}
+
+const value2 = { foo: 'bar' } as { foo: string } | string | null
+
+if (isObject(value2)) {
+ // value is { foo: string }
+} else {
+ // value is string | null
+}
+
+const value3 = { foo: 'bar' } as object | string
+
+if (isObject(value3)) {
+ // value is object
+} else {
+ // value is string
+}
+```
+
+## assertObject
+
+A Type Assertion function for checking if a value is an Object.
+
+### Basic Usage
+
+```typescript
+function assertObject(target: unknown, errorMessage?: ErrorMessage): asserts target is object
+```
+
+#### params
+
+- `target` .. The value to check.
+- `errorMessage` .. (optional) The error message to be displayed when the value is not an Object.
+
+#### returns
+
+- `void` .. When the value is an Object.
+
+Object here means a value that is not null, not an Array, and has a type of 'object'.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not an Object.
+
+Object here means a value that is not null, not an Array, and has a type of 'object'.
+
+### Example
+
+```typescript
+import { assertObject } from 'type-assurer'
+
+const value: unknown = { foo: 'bar' }
+
+assertObject(value)
+// When the value is not an Object, TypeAssertionError is thrown.
+// value is Record
+
+const value2 = { foo: 'bar' } as { foo: string } | string | null
+
+assertObject(value2)
+// When the value is not an Object, TypeAssertionError is thrown.
+// value2 is { foo: string }
+
+const value3 = { foo: 'bar' } as object | string
+
+assertObject(value3)
+// When the value is not an Object, TypeAssertionError is thrown.
+// value3 is object
+```
+
+## ensureObject
+
+Ensure that the value is an Object. If it is not an Object, throw an error.
+
+### Basic Usage
+
+```typescript
+function ensureObject(target: unknown, errorMessage?: ErrorMessage): object
+```
+
+#### params
+
+- `target` .. The value to check.
+- `errorMessage` .. (optional) The error message to be displayed when the value is not an Object.
+
+#### returns
+
+- `object` .. When the value is an Object.
+
+Object here means a value that is not null, not an Array, and has a type of 'object'.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not an Object.
+
+Object here means a value that is not null, not an Array, and has a type of 'object'.
+
+### Example
+
+```typescript
+import { ensureObject } from 'type-assurer'
+
+function getObject(): unknown { return { foo: 'bar' } }
+
+const result = ensureObject(getObject())
+// When the value is not an Object, throw TypeAssertionError
+// result is Record
+
+function getObject2(): { foo: string } | string { return { foo: 'bar' } }
+
+const result2 = ensureObject(getObject2())
+// When the value is not an Object, throw TypeAssertionError
+// result2 is { foo: string }
+
+function getObject3(): object | string { return { foo: 'bar' } }
+
+const result3 = ensureObject(getObject3())
+// When the value is not an Object, throw TypeAssertionError
+// result3 is object
+```
+
+## fallbackObject
+
+Fallback to the default value if the value is not an Object.
+
+### Basic Usage
+
+```typescript
+function fallbackObject(target: unknown, defaultValue: object): object
+```
+
+#### params
+
+- `target` .. The value to check.
+- `defaultValue` .. The default value to be returned when the value is not an Object.
+
+Object here means a value that is not null, not an Array, and has a type of 'object'.
+
+#### returns
+
+- `object` .. When the value is an Object. Or the default value when the value is not an Object.
+
+### Example
+
+```typescript
+import { fallbackObject } from 'type-assurer'
+
+function getObject(): unknown { return { foo: 'bar' } }
+
+const result = fallbackObject(getObject(), { foo: 'baz' })
+// When the value is not an Object, result is { foo: 'baz' }
+// result is Record
+
+function getObject2(): { foo: string } | string { return { foo: 'bar' } }
+
+const result2 = fallbackObject(getObject2(), { baz: 'qux' })
+// When the value is not an Object, result2 is { foo: 'baz' }
+// result2 is { foo: string } | { baz: string }
+
+function getObject3(): object | string { return { foo: 'bar' } }
+
+const result3 = fallbackObject(getObject3(), { baz: 'qux' })
+// When the value is not an Object, result3 is { baz: 'qux' }
+// result3 is object
+```
diff --git a/docs/src/content/docs/reference/typeGuards/promise.md b/docs/src/content/docs/reference/typeGuards/promise.md
new file mode 100644
index 0000000..e4fa90d
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/promise.md
@@ -0,0 +1,179 @@
+---
+title: promise
+description: A Type Guard Utility functions for checking if a value is a Promise.
+---
+A Type Guard Utility functions for checking if a value is a Promise.
+
+## Example of return value
+
+| input | result |
+| ----- | ------ |
+| Promise
(e.g. `Promise.resolve('foo')`) | true |
+| Promise object
(e.g. `new Promise(() => {})`) | true |
+| awaited async function
(e.g. `await fetchData()`) | true |
+| Promise like object
(e.g. `{ then: () => {} }`) | false |
+| other
(e.g. `null`, `undefined`, `0`, `''`, `false`, `true`, `[]`, `{}`) | false |
+
+## isPromise
+
+A Type Guard function for checking if a value is a Promise.
+
+This determination is made by `instanceof Promise`.
+Therefore, PromiseLike objects with a then method will be judged as false.
+If you want to make this true, see isAwaitable.
+
+### Basic Usage
+
+```typescript
+function isPromise(target: unknown): target is Promise
+```
+
+#### params
+
+- `target` .. The value to check.
+
+#### returns
+
+- `true` .. When the value is a Promise.
+- `false` .. When the value is not a Promise.
+
+### Examples
+
+```typescript
+import { isPromise } from 'type-assurer'
+
+const value: unknown = Promise.resolve('foo')
+
+if (isPromise(value)) {
+ // value is Promise
+} else {
+ // value is unknown
+}
+
+const value2: Promise | string = Promise.resolve('foo')
+
+if (isPromise(value2)) {
+ // value2 is Promise
+} else {
+ // value2 is string
+}
+```
+
+## assertPromise
+
+A Type Assertion function for checking if a value is a Promise.
+
+### Basic Usage
+
+```typescript
+function assertPromise(target: unknown, errorMessage?: ErrorMessage): asserts target is Promise
+```
+
+#### params
+
+- `target` .. The value to check.
+- `errorMessage` .. (optional) The error message to be displayed when the value is not a Promise.
+
+#### returns
+
+- `void` .. When the value is a Promise.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a Promise.
+
+### Examples
+
+```typescript
+import { assertPromise } from 'type-assurer'
+
+const value: unknown = Promise.resolve('foo')
+
+assertPromise(value)
+// When the value is not a Promise, TypeAssertionError is thrown.
+// value is Promise
+
+const value2: Promise | string = Promise.resolve('foo')
+
+assertPromise(value2)
+// When the value is not a Promise, TypeAssertionError is thrown.
+// value2 is Promise
+```
+
+## ensurePromise
+
+Ensure that the value is a Promise. If it is not a Promise, throw an error.
+
+### Basic Usage
+
+```typescript
+function ensurePromise(target: unknown, errorMessage?: ErrorMessage): Promise
+```
+
+#### params
+
+- `target` .. The value to check.
+- `errorMessage` .. (optional) The error message to be displayed when the value is not a Promise.
+
+#### returns
+
+- `Promise` .. When the value is a Promise.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a Promise.
+
+### Examples
+
+```typescript
+import { ensurePromise } from 'type-assurer'
+
+declare function fetchData(): unknown
+
+const result = await ensurePromise(fetchData())
+// When the value is not a Promise, TypeAssertionError is thrown.
+// result is Promise
+
+declare function fetchData2(): Promise | string
+
+const result2 = await ensurePromise(fetchData2())
+// When the value is not a Promise, TypeAssertionError is thrown.
+// result2 is Promise
+```
+
+## fallbackPromise
+
+Fallback to the fallback value if the value is not a Promise.
+
+### Basic Usage
+
+```typescript
+function fallbackPromise(target: unknown, fallbackValue: Promise): Promise
+```
+
+#### params
+
+- `target` .. The value to check.
+- `fallbackValue` .. The fallback value to be returned when the value is not a Promise.
+
+#### returns
+
+- `Promise` .. When the value is a Promise. Otherwise, the fallback value is returned.
+
+### Examples
+
+```typescript
+import { fallbackPromise } from 'type-assurer'
+
+declare function fetchData(): unknown
+
+const result = await fallbackPromise(fetchData(), Promise.resolve('fallback'))
+// When the value is not a Promise, fallback value is returned.
+// result is Promise
+
+declare function fetchData2(): Promise | string
+
+const result2 = await fallbackPromise(fetchData2(), Promise.resolve('fallback'))
+// When the value is not a Promise, fallback value is returned.
+// result2 is Promise
+```
diff --git a/docs/src/content/docs/reference/typeGuards/string.md b/docs/src/content/docs/reference/typeGuards/string.md
new file mode 100644
index 0000000..f58645c
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/string.md
@@ -0,0 +1,180 @@
+---
+title: string
+description: A Type Guard Utility functions for checking if a value is a string.
+---
+A Type Guard Utility functions for checking if a value is a string.
+
+## Example of return value
+
+| input | result |
+| ----- | ------ |
+| string
(e.g. `'foo'`) | true |
+| empty string
(e.g. `''`) | true |
+| string object
(e.g. `new String()`) | false |
+| object including `Symbol.toPrimitive`
(e.g. `{ [Symbol.toPrimitive]: () => 'foo' }`) | false |
+| object including `toString`
(e.g. `{ toString: () => 'foo' }`) | false |
+| object including `valueOf`
(e.g. `{ valueOf: () => 'foo' }`) | false |
+| other
(e.g. `0`, `null`, `undefined`, `{}`, `[]`) | false |
+
+## isString
+
+A Type Guard function for checking if a value is a string.
+
+This function is determined by `typeof target === 'string'`.
+Therefore, String Object and objects with `toString` `Symbol.toPrimitive` are judged as false.
+
+### Basic Usage
+
+```typescript
+function isString(target: unknown): target is string
+```
+
+#### params
+
+- `target` .. The value to check.
+
+#### returns
+
+- `true` .. When the value is a string.
+- `false` .. When the value is not a string.
+
+### Examples
+
+```typescript
+import { isString } from 'type-assurer'
+
+const value: unknown = 'foo'
+
+if (isString(value)) {
+ // value is string
+} else {
+ // value is unknown
+}
+
+const value2: string | number = 'foo'
+
+if (isString(value2)) {
+ // value2 is string
+} else {
+ // value2 is number
+}
+```
+
+## assertString
+
+A Type Assertion function for checking if a value is a string.
+
+### Basic Usage
+
+```typescript
+function assertString(target: unknown, errorMessage?: ErrorMessage): asserts target is string
+```
+
+#### params
+
+- `target` .. The value to check.
+- `errorMessage` .. (optional) The error message to be displayed when the value is not a string.
+
+#### returns
+
+- `void` .. When the value is a string.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a string.
+
+### Examples
+
+```typescript
+import { assertString } from 'type-assurer'
+
+const value: unknown = 'foo'
+
+assertString(value)
+// When the value is not string, throw TypeAssertionError
+// value is string
+
+const value2: string | number = 'foo'
+
+assertString(value2)
+// When the value is number, throw TypeAssertionError
+// value2 is string
+```
+
+## ensureString
+
+Ensure that the value is a string. If it is not a string, throw an error.
+
+### Basic Usage
+
+```typescript
+function ensureString(target: unknown, errorMessage?: ErrorMessage): string
+```
+
+#### params
+
+- `target` .. The value to check.
+- `errorMessage` .. (optional) The error message to be displayed when the value is not a string.
+
+#### returns
+
+- `string` .. When the value is a string.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a string.
+
+### Examples
+
+```typescript
+import { ensureString } from 'type-assurer'
+
+function getValue(): string { return 'foo' }
+
+const result = ensureString(getValue())
+// When result is not string, throw TypeAssertionError
+// result is string
+
+function getValue2(): 'foo' { return 'foo' }
+
+const result2 = ensureString(getValue2())
+// When result2 is not string, throw TypeAssertionError
+// result2 is 'foo'
+```
+
+## fallbackString
+
+Fallback to the default value if the value is not a string.
+
+### Basic Usage
+
+```typescript
+function fallbackString(target: unknown, defaultValue: string): string
+```
+
+#### params
+
+- `target` .. The value to check.
+- `defaultValue` .. The default value to be returned when the value is not a string.
+
+#### returns
+
+- `string` .. When the value is a string. Or the default value when the value is not a string.
+
+### Examples
+
+```typescript
+import { fallbackString } from 'type-assurer'
+
+function getValue(): string { return 'foo' }
+
+const result = fallbackString(getValue(), 'bar')
+// When result is not string, result is 'bar'
+// result is string
+
+function getValue2(): 'foo' { return 'foo' }
+
+const result2 = fallbackString(getValue2(), 'bar')
+// When result2 is not string, result2 is 'bar'
+// result2 is 'foo' | 'bar'
+```
diff --git a/docs/src/content/docs/reference/typeGuards/symbol.md b/docs/src/content/docs/reference/typeGuards/symbol.md
new file mode 100644
index 0000000..cfcc27b
--- /dev/null
+++ b/docs/src/content/docs/reference/typeGuards/symbol.md
@@ -0,0 +1,183 @@
+---
+title: symbol
+description: A Type Guard Utility functions for checking if a value is a symbol.
+---
+A Type Guard Utility functions for checking if a value is a symbol.
+
+## Example of return value
+
+| input | result |
+| ----- | ------ |
+| symbol
(e.g. `Symbol('foo')`) | true |
+| other
(e.g. `0`, `null`, `undefined`, `{}`, `[]`) | false |
+
+## isSymbol
+
+A Type Guard function for checking if a value is a symbol.
+
+This function is determined by `typeof target === 'symbol'`.
+
+### Basic Usage
+
+```typescript
+function isSymbol(target: unknown): target is symbol
+```
+
+#### params
+
+- `target` .. The value to check.
+
+#### returns
+
+- `true` .. When the value is a symbol.
+- `false` .. When the value is not a symbol.
+
+### Examples
+
+```typescript
+import { isSymbol } from 'type-assurer'
+
+const value: unknown = Symbol('foo')
+
+if (isSymbol(value)) {
+ // value is symbol
+} else {
+ // value is unknown
+}
+
+const symbol1: unique symbol = Symbol('bar')
+const symbol2: unique symbol = Symbol('baz')
+const value2: typeof symbol1 | typeof symbol2 | undefined = symbol1
+
+if (isSymbol(value2)) {
+ // value2 is typeof symbol1 | typeof symbol2
+} else {
+ // value2 is undefined
+}
+```
+
+## assertSymbol
+
+A Type Guard function for checking if a value is a symbol.
+
+### Basic Usage
+
+```typescript
+function assertSymbol(target: unknown, message?: ErrorMessage): asserts target is symbol
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. (optional) The error message to be displayed when the value is not a symbol.
+
+#### returns
+
+- `void` .. When the value is a symbol.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a symbol.
+
+### Examples
+
+```typescript
+import { assertSymbol } from 'type-assurer'
+
+const value: unknown = Symbol('foo')
+
+assertSymbol(value)
+// When the value is not a symbol, TypeAssertionError is thrown.
+// value is symbol
+
+const symbol1: unique symbol = Symbol('bar')
+const symbol2: unique symbol = Symbol('baz')
+const value2: typeof symbol1 | typeof symbol2 | undefined = symbol1
+
+assertSymbol(value2)
+// When the value is not a symbol, TypeAssertionError is thrown.
+// value2 is typeof symbol1 | typeof symbol2
+```
+
+## ensureSymbol
+
+Ensure that the value is a symbol.
+
+### Basic Usage
+
+```typescript
+function ensureSymbol(target: unknown, message?: ErrorMessage): symbol
+```
+
+#### params
+
+- `target` .. The value to check.
+- `message` .. (optional) The error message to be displayed when the value is not a symbol.
+
+#### returns
+
+- `symbol` .. When the value is a symbol.
+
+#### throws
+
+- `TypeAssertionError` .. When the value is not a symbol.
+
+### Examples
+
+```typescript
+import { ensureSymbol } from 'type-assurer'
+
+function getValue(): unknown { return Symbol('foo') }
+
+const value = ensureSymbol(getValue())
+// When the value is not a symbol, TypeAssertionError is thrown.
+// value is symbol
+
+const symbol1: unique symbol = Symbol('bar')
+const symbol2: unique symbol = Symbol('baz')
+function getValue2(): typeof symbol1 | typeof symbol2 | undefined { return symbol1 }
+
+const value2 = ensureSymbol(getValue2())
+// When the value is not a symbol, TypeAssertionError is thrown.
+// value2 is typeof symbol1 | typeof symbol2
+```
+
+## fallbackSymbol
+
+A Type Guard function for checking if a value is a symbol.
+
+### Basic Usage
+
+```typescript
+function fallbackSymbol(target: unknown, fallbackValue: symbol): symbol
+```
+
+#### params
+
+- `target` .. The value to check.
+- `fallbackValue` .. The value to return when the value is not a symbol.
+
+#### returns
+
+- `symbol` .. When the value is a symbol. If the value is not a symbol, return the fallback value.
+
+### Examples
+
+```typescript
+import { fallbackSymbol } from 'type-assurer'
+
+function getValue(): unknown { return Symbol('foo') }
+const fallbackSymbol = Symbol('bar')
+
+const value = fallbackSymbol(getValue(), fallbackSymbol)
+// When the value is not a symbol, fallbackSymbol is returned.
+// value is symbol
+
+const symbol1: unique symbol = Symbol('baz')
+function getValue2(): typeof symbol1 | undefined { return symbol1 }
+const fallbackSymbol2: unique symbol = Symbol('qux')
+
+const value2 = fallbackSymbol(getValue2(), fallbackSymbol2)
+// When the value is not a symbol, fallbackSymbol2 is returned.
+// value is typeof symbol1 | typeof fallbackSymbol2
+```
diff --git a/docs/src/env.d.ts b/docs/src/env.d.ts
new file mode 100644
index 0000000..acef35f
--- /dev/null
+++ b/docs/src/env.d.ts
@@ -0,0 +1,2 @@
+///
+///
diff --git a/package.json b/package.json
index ee4a900..256b33b 100644
--- a/package.json
+++ b/package.json
@@ -24,30 +24,32 @@
"access": "public"
},
"scripts": {
- "dev": "vitest",
+ "dev": "vitest --ui --coverage --typecheck",
+ "doc": "astro dev --root ./docs --open",
"build": "tsup",
- "test": "run-p test:*",
- "test:spec": "vitest --run",
- "test:spec-d": "vitest typecheck --run",
+ "doc-build": "astro check --root ./docs && astro build --root ./docs",
+ "preview": "astro preview --root ./docs",
+ "test": "yarn test:spec & yarn test:type",
+ "test:spec": "vitest --run --typecheck",
"test:type": "tsc --noEmit -p tsconfig.json",
- "lint": "eslint --ext .ts .",
- "format": "prettier --write . --ignore-path=.eslintignore"
+ "format": "biome format --write ./src ./docs",
+ "lint": "biome check --apply ./src ./docs"
},
"devDependencies": {
+ "@astrojs/check": "^0.3.1",
+ "@astrojs/starlight": "^0.14.0",
+ "@biomejs/biome": "^1.4.1",
"@changesets/changelog-github": "^0.4.8",
"@changesets/cli": "^2.26.2",
"@types/lodash": "^4.14.201",
- "@typescript-eslint/eslint-plugin": "^6.11.0",
- "@typescript-eslint/parser": "^6.11.0",
- "eslint": "^8.54.0",
- "eslint-config-prettier": "^9.0.0",
- "eslint-plugin-import": "^2.29.0",
+ "@vitest/coverage-v8": "^1.0.4",
+ "@vitest/ui": "^1.0.4",
+ "astro": "^3.6.4",
"lodash": "^4.17.21",
- "prettier": "^3.1.0",
+ "sharp": "^0.32.5",
"tsup": "^8.0.0",
- "typescript": "^5.2.2",
- "vitest": "^0.34.6",
- "yarn-run-all": "latest"
+ "typescript": "^5.3.2",
+ "vitest": "^1.0.0"
},
"peerDependencies": {
"typescript": ">= 4.0.0"
diff --git a/src/.DS_Store b/src/.DS_Store
new file mode 100644
index 0000000..08d4fee
Binary files /dev/null and b/src/.DS_Store differ
diff --git a/src/index.ts b/src/index.ts
index e4f19c5..eaf6d45 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,4 +1,10 @@
export * from './typeGuards'
-export type * from './lib/type'
-export { TypeAssertionError, errorMessage } from './lib/error'
-export { createGuard, createAssertion, createEnsure, createFallback, not } from './lib/factory'
+export {
+ TypeAssertionError,
+ errorMessage,
+ createGuard,
+ createAssertion,
+ createEnsure,
+ createFallback,
+ not,
+} from './lib'
diff --git a/src/lib-test/index.ts b/src/lib-test/index.ts
new file mode 100644
index 0000000..dea8220
--- /dev/null
+++ b/src/lib-test/index.ts
@@ -0,0 +1,3 @@
+export * from './tester'
+export * from './type'
+export * from './value'
diff --git a/src/lib-test/tester.ts b/src/lib-test/tester.ts
new file mode 100644
index 0000000..d31e1ba
--- /dev/null
+++ b/src/lib-test/tester.ts
@@ -0,0 +1,246 @@
+import { expect, test } from 'vitest'
+import type { Not, TypeAssert, TypeEnsure, TypeFallback, TypeGuard } from '~/lib'
+import { ValueType } from './type'
+import { type PickTypesOption, type TestOption, allTypes, getGenerator, testTypes } from './value'
+
+type ExpectGuard = (v: unknown) => boolean
+
+function xor(a: boolean | null | undefined, b: boolean | null | undefined): boolean {
+ return Boolean(a) !== Boolean(b)
+}
+
+/**
+ * specifies TypeGuard function retuens should be same as lodash function
+ *
+ * @param actualGuard set TypeGuard function
+ * @param expectGuard set Expected TypeGuard function (e.g. lodash)
+ * @param opt
+ */
+export function testEquivalentGuard(
+ actualGuard: TypeGuard | Not,
+ expectGuard: ExpectGuard,
+ opt: TestOption = {},
+): void {
+ const testcases = allTypes().map((type) => {
+ const expected = xor(expectGuard(getGenerator(type)()), opt.negative)
+ return { expected, type, case: `should return ${expected} when the value type is ${type}` }
+ })
+
+ test.each(testcases)('$case', ({ type, expected }) => {
+ const generate = getGenerator(type)
+ expect(actualGuard(generate())).toBe(expected)
+ })
+}
+
+/**
+ * specifies TypeGuard function returns should be true only specified ValueType.
+ *
+ * @param actualGuard set TypeGuard function
+ * @param expectedValueTypes set expected ValueType array
+ * @param opt
+ */
+export function testGuard(
+ actualGuard: TypeGuard | Not,
+ expectedValueTypes: ValueType[],
+ opt: TestOption & PickTypesOption = {},
+): void {
+ const testcases = testTypes(expectedValueTypes, opt).map((type) => {
+ const expected = xor(expectedValueTypes.includes(type), opt.negative)
+ return { expected, type, case: `should return ${expected} when the value type is ${type}` }
+ })
+
+ test.each(testcases)('$case', ({ type, expected }) => {
+ const generate = getGenerator(type)
+ expect(actualGuard(generate())).toBe(expected)
+ })
+}
+
+/**
+ * specifies TypeAssert of InvertedTypeAssert function should throw or not that same as lodash function condition
+ *
+ * @param actualAssert set TypeAssert function (if opt.negative is true, set InvertedTypeAssert function)
+ * @param expectGuard set Expected TypeGuard function (e.g. lodash)
+ * @param opt
+ */
+export function testEquivalentAssert(actualAssert: TypeAssert, expectGuard: ExpectGuard, opt: TestOption = {}): void {
+ const testcases = allTypes().map((type) => {
+ const expected = xor(expectGuard(getGenerator(type)()), opt.negative)
+ return { expected, type, case: `should ${expected ? 'NOT ' : ''}throw when the value type is ${type}` }
+ })
+
+ test.each(testcases)('$case', ({ type, expected }) => {
+ const generate = getGenerator(type)
+
+ if (expected) {
+ expect(() => actualAssert(generate())).not.toThrow()
+ } else {
+ expect(() => actualAssert(generate())).toThrow()
+ }
+ })
+}
+
+/**
+ *
+ * @param actualAssert
+ * @param expectedValueTypes
+ * @param opt
+ */
+export function testAssert(
+ actualAssert: TypeAssert,
+ expectedValueTypes: ValueType[],
+ opt: TestOption & PickTypesOption = {},
+): void {
+ const testcases = testTypes(expectedValueTypes, opt).map((type) => {
+ const expected = xor(expectedValueTypes.includes(type), opt.negative)
+ return { expected, type, case: `should ${expected ? 'NOT ' : ''}throw when the value type is ${type}` }
+ })
+
+ test.each(testcases)('$case', ({ type, expected }) => {
+ const generate = getGenerator(type)
+
+ if (expected) {
+ expect(() => actualAssert(generate())).not.toThrow()
+ } else {
+ expect(() => actualAssert(generate())).toThrow()
+ }
+ })
+}
+
+/**
+ * specifies TypeEnsure of InvertedTypeEnsure function should return or throw that same as lodash function condition
+ *
+ * @param ensure set TypeEnsure function (if opt.negative is true, set InvertedTypeEnsure function)
+ * @param expectGuard set Expected TypeGuard function (e.g. lodash)
+ * @param opt
+ */
+export function testEquivalentEnsure(ensure: TypeEnsure, expectGuard: ExpectGuard, opt: TestOption = {}): void {
+ const testcases = allTypes().map((type) => {
+ const expected = xor(expectGuard(getGenerator(type)()), opt.negative)
+ return {
+ expected,
+ type,
+ case: expected
+ ? `should return the value when the value type is ${type}`
+ : `should throw when the value type is ${type}`,
+ }
+ })
+
+ test.each(testcases)('$case', ({ type, expected }) => {
+ const generate = getGenerator(type)
+
+ if (expected) {
+ const value = generate()
+ expect(ensure(value)).toEqual(value)
+ } else {
+ expect(() => ensure(generate())).toThrow()
+ }
+ })
+}
+
+/**
+ * specifies TypeEnsure function should return or throw only specified ValueType.
+ *
+ * @param ensure set TypeEnsure function
+ * @param expectedValueTypes set expected ValueType array
+ * @param opt
+ */
+export function testEnsure(
+ ensure: TypeEnsure,
+ expectedValueTypes: ValueType[],
+ opt: TestOption & PickTypesOption = {},
+): void {
+ const testcases = testTypes(expectedValueTypes, opt).map((type) => {
+ const expected = xor(expectedValueTypes.includes(type), opt.negative)
+ return {
+ expected,
+ type,
+ case: expected
+ ? `should return the value when the value type is ${type}`
+ : `should throw when the value type is ${type}`,
+ }
+ })
+
+ test.each(testcases)('$case', ({ type, expected }) => {
+ const generate = getGenerator(type)
+
+ if (expected) {
+ const value = generate()
+ expect(ensure(value)).toEqual(value)
+ } else {
+ expect(() => ensure(generate())).toThrow()
+ }
+ })
+}
+
+// biome-ignore lint/suspicious/noExplicitAny:
+type AnyFunction = (...args: any[]) => any
+
+/**
+ * specifies TypeFallback of InvertedTypeFallback function should return that same as lodash function condition
+ *
+ * @param fallback set TypeFallback function (if opt.negative is true, set InvertedTypeFallback function)
+ * @param expectGuard set Expected TypeGuard function (e.g. lodash)
+ * @param opt
+ */
+export function testEquivalentFallback(
+ fallback: TypeFallback,
+ expectGuard: ExpectGuard,
+ opt: TestOption & { fallbackValue: unknown },
+): void
+
+// TypeFallback | InvertedTypeFallback is difficult to type safe, so use AnyFunction
+export function testEquivalentFallback(
+ fallback: AnyFunction,
+ expectGuard: ExpectGuard,
+ opt: TestOption & { fallbackValue: unknown },
+): void {
+ const testcases = allTypes().map((type) => {
+ const expected = xor(expectGuard(getGenerator(type)()), opt.negative)
+ return {
+ expected,
+ type,
+ case: `should return ${expected ? 'the value' : 'fallback value'} when the value type is ${type}`,
+ }
+ })
+
+ test.each(testcases)('$case', ({ type, expected }) => {
+ const generate = getGenerator(type)
+ const value = generate()
+
+ expect(fallback(value, opt.fallbackValue)).toEqual(expected ? value : opt.fallbackValue)
+ })
+}
+
+/**
+ * specifies TypeFallback function should return only specified ValueType.
+ *
+ * @param fallback set TypeFallback function
+ * @param expectedValueTypes set expected ValueType array
+ * @param opt
+ */
+export function testFallback(
+ fallback: TypeFallback,
+ expectedValueTypes: ValueType[],
+ opt: TestOption & PickTypesOption & { fallbackValue: unknown },
+): void
+
+export function testFallback(
+ fallback: AnyFunction,
+ expectedValueTypes: ValueType[],
+ opt: TestOption & PickTypesOption & { fallbackValue: unknown },
+): void {
+ const testcases = testTypes(expectedValueTypes, opt).map((type) => {
+ const expected = xor(expectedValueTypes.includes(type), opt.negative)
+ return {
+ expected,
+ type,
+ case: `should return ${expected ? 'the value' : 'fallback value'} when the value type is ${type}`,
+ }
+ })
+
+ test.each(testcases)('$case', ({ type, expected }) => {
+ const generate = getGenerator(type)
+ const value = generate()
+ expect(fallback(value, opt.fallbackValue)).toEqual(expected ? value : opt.fallbackValue)
+ })
+}
diff --git a/src/lib-test/type.ts b/src/lib-test/type.ts
new file mode 100644
index 0000000..e8c1182
--- /dev/null
+++ b/src/lib-test/type.ts
@@ -0,0 +1,531 @@
+export enum ValueType {
+ /**
+ * @description `true`
+ */
+ True = 'true',
+
+ /**
+ * @description `false`
+ */
+ False = 'false',
+
+ /**
+ * @description `Boolean(true)`
+ */
+ BooleanObject = 'booleanObject',
+
+ /**
+ * @description `{ [Symbol.toPrimitive]: () => true }`
+ */
+ ObjectToPrimitiveBoolean = 'objectToPrimitiveBoolean',
+
+ /**
+ * @description `{ valueOf: () => true }`
+ */
+ ObjectValueOfBoolean = 'objectValueOfBoolean',
+
+ /**
+ * @description `'true'`
+ */
+ BooleanParsableTrue = 'booleanParsableTrue',
+
+ /**
+ * @description `'false'`
+ */
+ BooleanParsableFalse = 'booleanParsableFalse',
+
+ /**
+ * @description `null`
+ */
+ Null = 'null',
+
+ /**
+ * @description `{ [Symbol.toPrimitive]: () => null }`
+ */
+ ObjectToPrimitiveNull = 'objectToPrimitiveNull',
+
+ /**
+ * @description `{ valueOf: () => null }`
+ */
+ ObjectValueOfNull = 'objectValueOfNull',
+
+ /**
+ * @description `undefined`
+ */
+ Undefined = 'undefined',
+
+ /**
+ * @description `{ [Symbol.toPrimitive]: () => undefined }`
+ */
+ ObjectToPrimitiveUndefined = 'objectToPrimitiveUndefined',
+
+ /**
+ * @description `{ valueOf: () => undefined }`
+ */
+ ObjectValueOfUndefined = 'objectValueOfUndefined',
+
+ /**
+ * @description `1`
+ */
+ PositiveNumber = 'positiveNumber',
+
+ /**
+ * @description `Infinity`
+ */
+ PositiveInfinity = 'positiveInfinity',
+
+ /**
+ * @description `0`
+ */
+ Zero = 'zero',
+
+ /**
+ * @description `-1`
+ */
+ NegativeNumber = 'negativeNumber',
+
+ /**
+ * @description `-Infinity`
+ */
+ NegativeInfinity = 'negativeInfinity',
+
+ /**
+ * @description `Number(1)`
+ */
+ NumberObject = 'numberObject',
+
+ /**
+ * @description `{ [Symbol.toPrimitive]: () => 1 }`
+ */
+ ObjectToPrimitiveNumber = 'objectToPrimitiveNumber',
+
+ /**
+ * @description `{ valueOf: () => 1 }`
+ */
+ ObjectValueOfNumber = 'objectValueOfNumber',
+
+ /**
+ * @description `1n`
+ */
+ PositiveBigInt = 'positiveBigint',
+
+ /**
+ * @description `-1n`
+ */
+ NegativeBigInt = 'negativeBigint',
+
+ /**
+ * @description `BigInt(1)`
+ */
+ BigIntObject = 'bigintObject',
+
+ /**
+ * @description `{ [Symbol.toPrimitive]: () => 1n }`
+ */
+ ObjectToPrimitiveBigInt = 'objectToPrimitiveBigint',
+
+ /**
+ * @description `{ valueOf: () => 1n }`
+ */
+ ObjectValueOfBigInt = 'objectValueOfBigint',
+
+ /**
+ * @description `NaN`
+ */
+ NaN = 'NaN',
+
+ /**
+ * @description `'123'`
+ */
+ NumberParsablePositiveInt = 'numberParsablePositiveInt',
+
+ /**
+ * @description `'0123'`
+ */
+ NumberStringLeadingZero = 'numberStringLeadingZero',
+
+ /**
+ * @description `'-123'`
+ */
+ NumberParsableNegativeInt = 'numberParsableNegativeInt',
+
+ /**
+ * @description `'123.456'`
+ */
+ NumberParsablePositiveFloat = 'numberParsablePositiveFloat',
+
+ /**
+ * @description `'-123.456'`
+ */
+ NumberParsableNegativeFloat = 'numberParsableNegativeFloat',
+
+ /**
+ * @description `'Infinity'`
+ */
+ NumberParsablePositiveInfinity = 'numberParsablePositiveInfinity',
+
+ /**
+ * @description `'-Infinity'`
+ */
+ NumberParsableNegativeInfinity = 'numberParsableNegativeInfinity',
+
+ /**
+ * @description `'foo'`
+ */
+ String = 'string',
+
+ /**
+ * @description `''`
+ */
+ EmptyString = 'emptyString',
+
+ /**
+ * @description `String('foo')`
+ */
+ StringObject = 'stringObject',
+
+ /**
+ * @description `{ [Symbol.toPrimitive]: () => 'foo' }`
+ */
+ ObjectToPrimitiveString = 'objectToPrimitiveString',
+
+ /**
+ * @description `{ valueOf: () => 'foo' }`
+ */
+ ObjectValueOfString = 'objectValueOfString',
+
+ /**
+ * @description `{ toString: () => 'foo' }`
+ */
+ ObjectToString = 'objectToString',
+
+ /**
+ * @description `'123'`
+ */
+ JsonParsableNumber = 'jsonParsableNumber',
+
+ /**
+ * @description `'true'`
+ */
+ JsonParsableTrue = 'jsonParsableTrue',
+
+ /**
+ * @description `'false'`
+ */
+ JsonParsableFalse = 'jsonParsableFalse',
+
+ /**
+ * @description `'null'`
+ */
+ JsonParsableNull = 'jsonParsableNull',
+
+ /**
+ * @description `'foo'`
+ */
+ JsonParsableString = 'jsonParsableString',
+
+ /**
+ * @description `'{"foo": "bar"}'`
+ */
+ JsonParsableObject = 'jsonParsableObject',
+
+ /**
+ * @description `'{"foo": { "bar": "baz" }, "qux": [1, 2, 3] }'`
+ */
+ JsonParsableComplexObject = 'jsonParsableComplexObject',
+
+ /**
+ * @description `'{}'`
+ */
+ JsonParsableEmptyObject = 'jsonParsableEmptyObject',
+
+ /**
+ * @description `'[1, 2, 3]'`
+ */
+ JsonParsableArray = 'jsonParsableArray',
+
+ /**
+ * @description `'[]'`
+ */
+ JsonParsableEmptyArray = 'jsonParsableEmptyArray',
+
+ /**
+ * @description `[1, 2, 3]`
+ */
+ Array = 'array',
+
+ /**
+ * @description `[]`
+ */
+ EmptyArray = 'emptyArray',
+
+ /**
+ * @description `Array(3)`
+ */
+ BlankArray = 'blankArray',
+
+ /**
+ * @description `document.body.children`
+ */
+ ArrayLike = 'arrayLike',
+
+ /**
+ * @description `new ArrayBuffer(8)`
+ */
+ ArrayBuffer = 'arrayBuffer',
+
+ /**
+ * @description `new Uint8Array(8)`
+ */
+ Uint8Array = 'uint8Array',
+
+ /**
+ * @description `new Uint8ClampedArray(8)`
+ */
+ Uint8ClampedArray = 'uint8ClampedArray',
+
+ /**
+ * @description `new Uint16Array(8)`
+ */
+ Uint16Array = 'uint16Array',
+
+ /**
+ * @description `new Uint32Array(8)`
+ */
+ Uint32Array = 'uint32Array',
+
+ /**
+ * @description `new Int8Array(8)`
+ */
+ Int8Array = 'int8Array',
+
+ /**
+ * @description `new Int16Array(8)`
+ */
+ Int16Array = 'int16Array',
+
+ /**
+ * @description `new Int32Array(8)`
+ */
+ Int32Array = 'int32Array',
+
+ /**
+ * @description `new Float32Array(8)`
+ */
+ Float32Array = 'float32Array',
+
+ /**
+ * @description `new Float64Array(8)`
+ */
+ Float64Array = 'float64Array',
+
+ /**
+ * @description `new BigInt64Array(8)`
+ */
+ BigInt64Array = 'bigint64Array',
+
+ /**
+ * @description `new BigUint64Array(8)`
+ */
+ BigUint64Array = 'biguint64Array',
+
+ /**
+ * @description `new SharedArrayBuffer(8)`
+ */
+ SharedArrayBuffer = 'sharedArrayBuffer',
+
+ /**
+ * @description `new DataView(new ArrayBuffer(8))`
+ */
+ DataView = 'dataView',
+
+ /**
+ * @description `new DataView(new ArrayBuffer(0))`
+ */
+ EmptyDataView = 'emptyDataView',
+
+ /**
+ * @description `Buffer.from('foo')`
+ */
+ Buffer = 'buffer',
+
+ /**
+ * @description `Buffer.alloc(0)`
+ */
+ EmptyBuffer = 'emptyBuffer',
+
+ /**
+ * @description `{ foo: 'bar' }`
+ */
+ Object = 'object',
+
+ /**
+ * @description `{ }`
+ */
+ EmptyObject = 'emptyObject',
+
+ /**
+ * @description `Object.create(null)`
+ */
+ BlankObject = 'blankObject',
+
+ /**
+ * @description `{ foo: [Circular] }`
+ */
+ RecursiveObject = 'recursiveObject',
+
+ /**
+ * @description `{ [Symbol.toStringTag]: () => 'Foo' }`
+ */
+ WellKnownSymbolObject = 'wellKnownSymbolObject',
+
+ /**
+ * @description `{ *[Symbol.iterator]() { yield 1 } }`
+ */
+ IterableObject = 'iterableObject',
+
+ /**
+ * @description `{ async *[Symbol.asyncIterator]() { yield 1 } }`
+ */
+ AsyncIterableObject = 'asyncIterableObject',
+
+ /**
+ * @description `{ foo: 'bar', baz: { toJSON: (k) => `${k}` } }`
+ */
+ JsonifiableObject = 'jsonifiableObject',
+
+ /**
+ * @description `[{ toJSON: (k) => `${k}` }]`
+ */
+ JsonifiableObjectInArray = 'jsonifiableObjectInArray',
+
+ /**
+ * @description `/foo/`
+ */
+ RegExp = 'regExp',
+
+ /**
+ * @description `() => void 0`
+ */
+ Function = 'function',
+
+ /**
+ * @description `async () => void 0`
+ */
+ AsyncFunction = 'asyncFunction',
+
+ /**
+ * @description `function* () { yield 1 }`
+ */
+ GeneratorFunction = 'generatorFunction',
+
+ /**
+ * @description `async function* () { yield 1 }`
+ */
+ AsyncGeneratorFunction = 'asyncGeneratorFunction',
+
+ /**
+ * @description `Symbol('foo')`
+ */
+ Symbol = 'symbol',
+
+ /**
+ * @description `{ [Symbol.toPrimitive]: () => Symbol('foo') }`
+ */
+ ObjectToPrimitiveSymbol = 'objectToPrimitiveSymbol',
+
+ /**
+ * @description `{ valueOf: () => Symbol('foo') }`
+ */
+ ObjectValueOfSymbol = 'objectValueOfSymbol',
+
+ /**
+ * @description `new Proxy({}, {})`
+ */
+ Proxy = 'proxy',
+
+ /**
+ * @description `new Promise(() => void 0)`
+ */
+ Promise = 'promise',
+
+ /**
+ * @description `{ then: () => void 0 }`
+ */
+ ThenableObject = 'thenableObject',
+
+ /**
+ * @description `{ const f = () => void 0; f.then = () => void 0; return f; }`
+ */
+ ThenableFunction = 'thenableFunction',
+
+ /**
+ * @description `new class { then() { } }`
+ */
+ ThenableInstance = 'thenableInstance',
+
+ /**
+ * @description `await Promise.resolve()`
+ */
+ Awaited = 'awaited',
+
+ /**
+ * @description `new Date()`
+ */
+ Date = 'date',
+
+ /**
+ * @description `new Error()`
+ */
+ Error = 'error',
+
+ /**
+ * @description `class Foo {}`
+ */
+ Class = 'class',
+
+ /**
+ * @description `new Foo()` where `class Foo {}`
+ */
+ ClassInstance = 'classInstance',
+
+ /**
+ * @description `new Map([['foo', 'bar']])`
+ */
+ Map = 'map',
+
+ /**
+ * @description `new Map()`
+ */
+ EmptyMap = 'emptyMap',
+
+ /**
+ * @description `new WeakMap([[{}, 'bar']])`
+ */
+ WeakMap = 'weakMap',
+
+ /**
+ * @description `new WeakMap()`
+ */
+ EmptyWeakMap = 'emptyWeakMap',
+
+ /**
+ * @description `new Set(['foo'])`
+ */
+ Set = 'set',
+
+ /**
+ * @description `new Set()`
+ */
+ EmptySet = 'emptySet',
+
+ /**
+ * @description `new WeakSet([{}])`
+ */
+ WeakSet = 'weakSet',
+
+ /**
+ * @description `new WeakSet()`
+ */
+ EmptyWeakSet = 'emptyWeakSet',
+}
diff --git a/src/lib-test/value.ts b/src/lib-test/value.ts
new file mode 100644
index 0000000..4421bde
--- /dev/null
+++ b/src/lib-test/value.ts
@@ -0,0 +1,241 @@
+/* eslint-disable max-lines */
+import { ValueType } from './type'
+
+type ValueFactory = () => unknown
+
+// WeakMap, WeakSet 用のキー
+const persistentObject1 = { key: 1 }
+Object.freeze(persistentObject1)
+
+const persistentObject2 = { key: 2 }
+Object.freeze(persistentObject2)
+
+const generators = {
+ [ValueType.True]: () => true,
+ [ValueType.False]: () => false,
+ [ValueType.BooleanObject]: () => new Boolean(true),
+ [ValueType.ObjectToPrimitiveBoolean]: () => ({ [Symbol.toPrimitive]: () => true }),
+ [ValueType.ObjectValueOfBoolean]: () => ({ valueOf: () => true }),
+ [ValueType.BooleanParsableTrue]: () => 'true',
+ [ValueType.BooleanParsableFalse]: () => 'false',
+ [ValueType.Null]: () => null,
+ [ValueType.ObjectToPrimitiveNull]: () => ({ [Symbol.toPrimitive]: () => null }),
+ [ValueType.ObjectValueOfNull]: () => ({ valueOf: () => null }),
+ [ValueType.Undefined]: () => undefined,
+ [ValueType.ObjectToPrimitiveUndefined]: () => ({ [Symbol.toPrimitive]: () => undefined }),
+ [ValueType.ObjectValueOfUndefined]: () => ({ valueOf: () => undefined }),
+ [ValueType.PositiveNumber]: () => 1,
+ [ValueType.PositiveInfinity]: () => Infinity,
+ [ValueType.Zero]: () => 0,
+ [ValueType.NegativeNumber]: () => -1,
+ [ValueType.NegativeInfinity]: () => -Infinity,
+ [ValueType.NumberObject]: () => new Number(1),
+ [ValueType.ObjectToPrimitiveNumber]: () => ({ [Symbol.toPrimitive]: () => 1 }),
+ [ValueType.ObjectValueOfNumber]: () => ({ valueOf: () => 1 }),
+ [ValueType.PositiveBigInt]: () => 1n,
+ [ValueType.NegativeBigInt]: () => -1n,
+ [ValueType.BigIntObject]: () => BigInt(1),
+ [ValueType.ObjectToPrimitiveBigInt]: () => ({ [Symbol.toPrimitive]: () => 1n }),
+ [ValueType.ObjectValueOfBigInt]: () => ({ valueOf: () => 1n }),
+ [ValueType.NaN]: () => NaN,
+ [ValueType.NumberParsablePositiveInt]: () => '123',
+ [ValueType.NumberStringLeadingZero]: () => '0123',
+ [ValueType.NumberParsableNegativeInt]: () => '-123',
+ [ValueType.NumberParsablePositiveFloat]: () => '123.456',
+ [ValueType.NumberParsableNegativeFloat]: () => '-123.456',
+ [ValueType.NumberParsablePositiveInfinity]: () => 'Infinity',
+ [ValueType.NumberParsableNegativeInfinity]: () => '-Infinity',
+ [ValueType.String]: () => 'foo',
+ [ValueType.EmptyString]: () => '',
+ [ValueType.StringObject]: () => new String('foo'),
+ [ValueType.ObjectToPrimitiveString]: () => ({ [Symbol.toPrimitive]: () => 'foo' }),
+ [ValueType.ObjectValueOfString]: () => ({ valueOf: () => 'foo' }),
+ [ValueType.ObjectToString]: () => ({ toString: () => 'foo' }),
+ [ValueType.JsonParsableNumber]: () => '123',
+ [ValueType.JsonParsableTrue]: () => 'true',
+ [ValueType.JsonParsableFalse]: () => 'false',
+ [ValueType.JsonParsableNull]: () => 'null',
+ [ValueType.JsonParsableString]: () => '"foo"',
+ [ValueType.JsonParsableObject]: () => '{"foo":"bar"}',
+ [ValueType.JsonParsableComplexObject]: () => '{"foo":{"bar":"baz"}, "qux": [1,2,3]}',
+ [ValueType.JsonParsableEmptyObject]: () => '{}',
+ [ValueType.JsonParsableArray]: () => '[1,2,3]',
+ [ValueType.JsonParsableEmptyArray]: () => '[]',
+ [ValueType.Array]: () => [1, 2, 3],
+ [ValueType.EmptyArray]: () => [],
+ [ValueType.BlankArray]: () => Array(3),
+ [ValueType.ArrayLike]: () => ({ length: 3 }),
+ [ValueType.ArrayBuffer]: () => new ArrayBuffer(8),
+ [ValueType.Uint8Array]: () => new Uint8Array([1, 2, 3]),
+ [ValueType.Uint8ClampedArray]: () => new Uint8ClampedArray([1, 2, 3]),
+ [ValueType.Uint16Array]: () => new Uint16Array([1, 2, 3]),
+ [ValueType.Uint32Array]: () => new Uint32Array([1, 2, 3]),
+ [ValueType.Int8Array]: () => new Int8Array([1, 2, 3]),
+ [ValueType.Int16Array]: () => new Int16Array([1, 2, 3]),
+ [ValueType.Int32Array]: () => new Int32Array([1, 2, 3]),
+ [ValueType.Float32Array]: () => new Float32Array([1, 2, 3]),
+ [ValueType.Float64Array]: () => new Float64Array([1, 2, 3]),
+ [ValueType.BigInt64Array]: () => new BigInt64Array([1n, 2n, 3n]),
+ [ValueType.BigUint64Array]: () => new BigUint64Array([1n, 2n, 3n]),
+ [ValueType.SharedArrayBuffer]: () => new SharedArrayBuffer(8),
+ [ValueType.DataView]: () => new DataView(new ArrayBuffer(8)),
+ [ValueType.EmptyDataView]: () => new DataView(new ArrayBuffer(0)),
+ [ValueType.Buffer]: () => Buffer.from('foo'),
+ [ValueType.EmptyBuffer]: () => Buffer.alloc(0),
+ [ValueType.Object]: () => ({ foo: 'bar' }),
+ [ValueType.EmptyObject]: () => ({}),
+ [ValueType.BlankObject]: () => Object.create(null),
+ [ValueType.RecursiveObject]: () => {
+ // biome-ignore lint/suspicious/noExplicitAny:
+ const obj: any = {}
+ obj.foo = obj
+ return obj
+ },
+ [ValueType.WellKnownSymbolObject]: () => ({ [Symbol.toStringTag]: () => 'Foo' }),
+ [ValueType.IterableObject]: () => ({
+ *[Symbol.iterator]() {
+ yield 1
+ },
+ }),
+ [ValueType.AsyncIterableObject]: () => ({
+ async *[Symbol.asyncIterator]() {
+ yield await 1
+ },
+ }),
+ [ValueType.JsonifiableObject]: () => ({
+ foo: 'bar',
+ // biome-ignore lint/style/useNamingConvention:
+ baz: { toJSON: (k: string | number) => `${k}` },
+ }),
+ // biome-ignore lint/style/useNamingConvention:
+ [ValueType.JsonifiableObjectInArray]: () => [{ toJSON: (k: string | number) => `${k}` }],
+ [ValueType.RegExp]: () => /foo/,
+ [ValueType.Proxy]: () => new Proxy({}, {}),
+ [ValueType.Promise]: () =>
+ new Promise(() => {
+ return
+ }),
+ [ValueType.ThenableObject]: () => ({
+ then: () => {
+ return
+ },
+ }),
+ [ValueType.ThenableFunction]: () => {
+ const fn = () => {
+ return
+ }
+ fn.then = () => {
+ return
+ }
+ return fn
+ },
+ [ValueType.ThenableInstance]: () =>
+ new (class Foo {
+ then() {
+ return
+ }
+ })(),
+ [ValueType.Awaited]: async () => await Promise.resolve(),
+ [ValueType.Date]: () => new Date(),
+ [ValueType.Error]: () => new Error(),
+ [ValueType.Class]: () =>
+ class Foo {
+ bar() {
+ return 'bar'
+ }
+ get baz() {
+ return 'baz'
+ }
+ qux = 'qux'
+ },
+ [ValueType.ClassInstance]: () =>
+ new (class Foo {
+ bar() {
+ return 'bar'
+ }
+ get baz() {
+ return 'baz'
+ }
+ qux = 'qux'
+ })(),
+ [ValueType.Map]: () => new Map([['foo', 'bar']]),
+ [ValueType.EmptyMap]: () => new Map(),
+ [ValueType.WeakMap]: () => new WeakMap([[persistentObject1, 'bar']]),
+ [ValueType.EmptyWeakMap]: () => new WeakMap(),
+ [ValueType.Set]: () => new Set([1, 2, 3]),
+ [ValueType.EmptySet]: () => new Set(),
+ [ValueType.WeakSet]: () => new WeakSet([persistentObject1, persistentObject2]),
+ [ValueType.EmptyWeakSet]: () => new WeakSet(),
+ [ValueType.Function]: () => () => {
+ return
+ },
+ [ValueType.AsyncFunction]: () => async () => {
+ await 0
+ return
+ },
+ [ValueType.GeneratorFunction]: () =>
+ function* () {
+ yield 1
+ },
+ [ValueType.AsyncGeneratorFunction]: () =>
+ async function* () {
+ yield await 1
+ },
+ [ValueType.Symbol]: () => Symbol('foo'),
+ [ValueType.ObjectToPrimitiveSymbol]: () => ({ [Symbol.toPrimitive]: () => Symbol('foo') }),
+ [ValueType.ObjectValueOfSymbol]: () => ({ valueOf: () => Symbol('foo') }),
+} as const satisfies Record>
+
+Object.freeze(generators)
+
+/**
+ * Returns a list of all ValueTypes.
+ */
+export function allTypes(): ValueType[] {
+ return Object.values(ValueType)
+}
+
+export interface PickTypesOption {
+ parsableString?: boolean
+ typedArray?: boolean
+}
+
+/**
+ * Returns a list of ValueTypes that you want to test by specifying expect targets.
+ * Here, Value Types that generate the same value (equivalent by '===') as the specified expect types are skipped.
+ */
+export function testTypes(expectTargets: ValueType[], opt: PickTypesOption = {}): ValueType[] {
+ const targetTypes = allTypes().filter((t) => {
+ let result = true
+
+ if (!opt.parsableString) {
+ result &&= !(t.toLocaleLowerCase().includes('parsable') || t.toLocaleLowerCase().includes('jsonifiable'))
+ }
+
+ if (!opt.typedArray) {
+ result &&= !(/^uint|int|float|bigInt|bigUint/.test(t) && t.endsWith('Array'))
+ }
+
+ return result
+ })
+
+ const cachedValues = targetTypes.reduce(
+ (acc, t): Partial> => {
+ acc[t] = getGenerator(t)()
+ return acc
+ },
+ {} as Partial>,
+ ) as Record
+
+ return targetTypes.filter(
+ (t) => expectTargets.includes(t) || !expectTargets.some((e) => cachedValues[t] === cachedValues[e]),
+ )
+}
+
+export function getGenerator(type: ValueType): () => unknown {
+ return generators[type]
+}
+
+export interface TestOption {
+ negative?: boolean
+}
diff --git a/src/lib/error/error.ts b/src/lib/error/error.ts
index fef423b..ae0b6c0 100644
--- a/src/lib/error/error.ts
+++ b/src/lib/error/error.ts
@@ -1,6 +1,9 @@
export class TypeAssertionError extends Error {
- constructor(message: string, public readonly actualData: unknown) {
- super(message)
+ public readonly actualData: unknown
+
+ constructor(message: string, _actualData: unknown, opt?: ErrorOptions) {
+ super(message, opt)
+ this.actualData = _actualData
this.name = 'TypeAssertionError'
}
}
diff --git a/src/lib/error/message.ts b/src/lib/error/message.ts
index 0064d68..b2ec6f4 100644
--- a/src/lib/error/message.ts
+++ b/src/lib/error/message.ts
@@ -7,18 +7,13 @@ function actualTypeOf(target: unknown): string {
if (target === null) {
return `null ${suffix}`
}
- return `object (constructor: ${target.constructor.name}) ${suffix}`
+ return `object (constructor: ${target.constructor?.name ?? 'object'}) ${suffix}`
}
-export function errorMessage(
- expectedType: string,
- { not }: { not?: boolean } = {}
-): (target: unknown) => string {
+export function errorMessage(expectedType: string, { not }: { not?: boolean } = {}): (target: unknown) => string {
if (not) {
return (actualValue) => {
- return `Expected a value not of type ${expectedType}, but received ${actualTypeOf(
- actualValue
- )}.`
+ return `Expected a value not of type ${expectedType}, but received ${actualTypeOf(actualValue)}.`
}
}
return (actualValue) => {
diff --git a/src/lib/factory.ts b/src/lib/factory.ts
index 862c55a..6c2a381 100644
--- a/src/lib/factory.ts
+++ b/src/lib/factory.ts
@@ -13,8 +13,8 @@ import type {
TypeErrorMessage,
TypeFallback,
TypeGuard,
- VoidAssert
-} from './type'
+ VoidAssert,
+} from './types'
import { TypeAssertionError } from './error'
@@ -119,10 +119,7 @@ export function not(guard: (arg: unknown) => boolean): Not {
* const assertString = createAssertion(isString, 'target must be a string')
* ```
*/
-export function createAssertion(
- guard: T,
- message: TypeErrorMessage
-): TypeAssertOf
+export function createAssertion(guard: T, message: TypeErrorMessage): TypeAssertOf
/**
* @description create a type assertion from a inverted type guard.
@@ -136,10 +133,7 @@ export function createAssertion(
* const assertNotString = createAssertion(not(isString), 'target must not be a string')
* ```
*/
-export function createAssertion(
- guard: Not,
- message: TypeErrorMessage
-): InvertedTypeAssertOf
+export function createAssertion(guard: Not, message: TypeErrorMessage): InvertedTypeAssertOf
/**
* @description create a type assertion from a type predicate.
@@ -169,7 +163,7 @@ export function createAssertion(guard: (target: unknown) => boolean, message: Ty
export function createAssertion(
guard: (target: unknown) => boolean,
- message: TypeErrorMessage
+ message: TypeErrorMessage,
): TypeAssert | InvertedTypeAssert | VoidAssert {
return ((target: unknown, overrideMessage?: TypeErrorMessage) => {
if (!guard(target)) {
@@ -190,7 +184,7 @@ export function createAssertion(
* const ensureString = createEnsure(isString, 'target must be a string')
* ```
*/
-export function createEnsure(guard: TypeGuard, message: TypeErrorMessage): TypeEnsureOf
+export function createEnsure(guard: T, message: TypeErrorMessage): TypeEnsureOf
/**
* @description create a type ensure from a inverted type guard.
@@ -220,7 +214,6 @@ export function createEnsure(guard: Not, message: TypeEr
*/
export function createEnsure(guard: (target: unknown) => target is T, message: TypeErrorMessage): TypeEnsure
-
/**
* @description create a type ensure from a type predicate. This is a type-unsafe version of `createEnsure`.
* @param guard {(arg: unknown) => boolean} type guard predicate
@@ -235,7 +228,7 @@ export function createEnsure(guard: (target: unknown) => boolean, message: TypeE
export function createEnsure(
guard: (target: unknown) => boolean,
- message: TypeErrorMessage
+ message: TypeErrorMessage,
): TypeEnsure | InvertedTypeEnsure {
return ((target: unknown, overrideMessage?: TypeErrorMessage) => {
const assert = createAssertion(guard, message)
@@ -268,9 +261,7 @@ export function createFallback(guard: T): TypeFallback(
- guard: Not
-): InvertedTypeFallback>
+export function createFallback(guard: Not): InvertedTypeFallback>
/**
* @description create a type fallback from a type predicate.
@@ -296,8 +287,8 @@ export function createFallback(guard: (target: unknown) => target is T): Type
*/
export function createFallback(guard: (target: unknown) => boolean): TypeFallback
-export function createFallback(
- guard: (target: unknown) => boolean
-): TypeFallback | InvertedTypeFallback {
- return ((target: unknown, fallback: unknown) => (guard(target) ? target : fallback)) as TypeFallback | InvertedTypeFallback
+export function createFallback(guard: (target: unknown) => boolean): TypeFallback | InvertedTypeFallback {
+ return ((target: unknown, fallback: unknown) => (guard(target) ? target : fallback)) as
+ | TypeFallback
+ | InvertedTypeFallback
}
diff --git a/src/lib/index.ts b/src/lib/index.ts
new file mode 100644
index 0000000..ecb03fa
--- /dev/null
+++ b/src/lib/index.ts
@@ -0,0 +1,3 @@
+export * from './error'
+export * from './factory'
+export * from './types'
diff --git a/src/lib/test/index.ts b/src/lib/test/index.ts
deleted file mode 100644
index c9968fd..0000000
--- a/src/lib/test/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './tester'
diff --git a/src/lib/test/tester.ts b/src/lib/test/tester.ts
deleted file mode 100644
index 9d75859..0000000
--- a/src/lib/test/tester.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import { expect, test } from 'vitest'
-import {
- InvertedTypeAssert,
- InvertedTypeEnsure,
- InvertedTypeFallback,
- TypeAssert,
- TypeEnsure,
- TypeFallback,
- TypeGuard,
- Not
-} from '../..'
-import { type TestOption, allTypes, getGenerator } from './value'
-
-type ExpectGuard = (v: unknown) => boolean
-
-function xor(a: boolean | null | undefined, b: boolean | null | undefined): boolean {
- return ((a as boolean) && (!b as boolean)) || ((!a as boolean) && (b as boolean))
-}
-
-/**
- * specifies TypeGuard function retuens should be same as lodash function
- *
- * @param actualGuard set TypeGuard function
- * @param expectGuard set lodash function
- * @param opt
- */
-export function testGuard(
- actualGuard: TypeGuard | Not,
- expectGuard: ExpectGuard,
- opt: TestOption = {}
-): void {
- test.each(allTypes())('test value type: %s', (type) => {
- const generate = getGenerator(type)
- if (opt.negative) {
- expect(actualGuard(generate())).not.toBe(expectGuard(generate()))
- } else {
- expect(actualGuard(generate())).toBe(expectGuard(generate()))
- }
- })
-}
-
-/**
- * specifies TypeAssert of InvertedTypeAssert function should throw or not that same as lodash function condition
- *
- * @param actualAssert set TypeAssert function (if opt.negative is true, set InvertedTypeAssert function)
- * @param expectGuard set lodash function
- * @param opt
- */
-export function testAssert(
- actualAssert: TypeAssert | InvertedTypeAssert,
- expectGuard: ExpectGuard,
- opt: TestOption = {}
-): void {
- test.each(allTypes())('test value type: %s', (type) => {
- const generate = getGenerator(type)
-
- if (xor(expectGuard(generate()), opt.negative)) {
- // (lodash.isString: true, negative: false) or (lodash.isString: false, negative: true)
- // assertString should not throw
-
- expect(() => actualAssert(generate())).not.toThrow()
- } else {
- // (lodash.isString: true, negative: true) or (lodash.isString: false, negative: false)
- // assertString should throw
-
- expect(() => actualAssert(generate())).toThrow()
- }
- })
-}
-
-/**
- * specifies TypeEnsure of InvertedTypeEnsure function should return or throw that same as lodash function condition
- *
- * @param ensure set TypeEnsure function (if opt.negative is true, set InvertedTypeEnsure function)
- * @param expectGuard set lodash function
- * @param opt
- */
-export function testEnsure(
- ensure: TypeEnsure | InvertedTypeEnsure,
- expectGuard: ExpectGuard,
- opt: TestOption = {}
-): void {
- test.each(allTypes())('test value type: %s', (type) => {
- const generate = getGenerator(type)
-
- if (xor(expectGuard(generate()), opt.negative)) {
- // (lodash.isString: true, negative: false) or (lodash.isString: false, negative: true)
- // ensureString should not throw and return value that same as argument
-
- const value = generate()
- expect(ensure(value)).toEqual(value)
- } else {
- // (lodash.isString: true, negative: true) or (lodash.isString: false, negative: false)
- // ensureString should throw
-
- expect(() => ensure(generate())).toThrow()
- }
- })
-}
-
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-type AnyFunction = (...args: any[]) => any
-
-/**
- * specifies TypeFallback of InvertedTypeFallback function should return that same as lodash function condition
- *
- * @param fallback set TypeFallback function (if opt.negative is true, set InvertedTypeFallback function)
- * @param expectGuard set lodash function
- * @param opt
- */
-export function testFallback(
- fallback: TypeFallback | InvertedTypeFallback,
- expectGuard: ExpectGuard,
- opt: TestOption & { fallbackValue: unknown }
-): void
-
-// TypeFallback | InvertedTypeFallback is difficult to type safe, so use AnyFunction
-export function testFallback(
- fallback: AnyFunction,
- expectGuard: ExpectGuard,
- opt: TestOption & { fallbackValue: unknown }
-): void {
- test.each(allTypes())('test value type: %s', (type) => {
- const generate = getGenerator(type)
- const value = generate()
-
- // (lodash.isString: true, negative: false) or (lodash.isString: false, negative: true)
- // fallbackString should return value that same as first argument
-
- // (lodash.isString: true, negative: true) or (lodash.isString: false, negative: false)
- // fallbackString should return fallback value
-
- const expected = xor(expectGuard(generate()), opt.negative) ? value : opt.fallbackValue
- expect(fallback(value, opt.fallbackValue)).toEqual(expected)
- })
-}
diff --git a/src/lib/test/type.ts b/src/lib/test/type.ts
deleted file mode 100644
index 7dd2921..0000000
--- a/src/lib/test/type.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-export enum ValueType {
- /**
- * @description `true`
- */
- True = 'true',
-
- /**
- * @description `false`
- */
- False = 'false',
-
- /**
- * @description `null`
- */
- Null = 'null',
-
- /**
- * @description `undefined`
- */
- Undefined = 'undefined',
-
- /**
- * @description `1`
- */
- PositiveNumber = 'positiveNumber',
-
- /**
- * @description `Infinity`
- */
- PositiveInfinity = 'positiveInfinity',
-
- /**
- * @description `0`
- */
- Zero = 'zero',
-
- /**
- * @description `-1`
- */
- NegativeNumber = 'negativeNumber',
-
- /**
- * @description `-Infinity`
- */
- NegativeInfinity = 'negativeInfinity',
-
- /**
- * @description `BigInt(1)`
- */
- PositiveBigInt = 'positiveBigint',
-
- /**
- * @description `BigInt(-1)`
- */
- NegativeBigInt = 'negativeBigint',
-
- /**
- * @description `NaN`
- */
- NaN = 'NaN',
-
- /**
- * @description `'foo'`
- */
- String = 'string',
-
- /**
- * @description `''`
- */
- EmptyString = 'emptyString',
-
- /**
- * @description `[1, 2, 3]`
- */
- Array = 'array',
-
- /**
- * @description `[]`
- */
- EmptyArray = 'emptyArray',
-
- /**
- * @description `Array(3)`
- */
- BlankArray = 'spacedArray',
-
- /**
- * @description `document.body.children`
- */
- ArrayLike = 'arrayLike',
-
- /**
- * @description `new ArrayBuffer(8)`
- */
- ArrayBuffer = 'arrayBuffer',
-
- /**
- * @description `{ foo: 'bar' }`
- */
- Object = 'object',
-
- /**
- * @description `{ }`
- */
- EmptyObject = 'emptyObject',
-
- /**
- * @description `{ foo: [Circular] }`
- */
- RecursiveObject = 'recursiveObject',
-
- /**
- * @description `() => void 0`
- */
- Function = 'function',
-
- /**
- * @description `async () => void 0`
- */
- AsyncFunction = 'asyncFunction',
-
- /**
- * @description `function* () { yield 1 }`
- */
- GeneratorFunction = 'generatorFunction',
-
- /**
- * @description `async function* () { yield 1 }`
- */
- AsyncGeneratorFunction = 'asyncGeneratorFunction',
-
- /**
- * @description `Symbol('foo')`
- */
- Symbol = 'symbol',
-
- /**
- * @description `new Proxy({}, {})`
- */
- Proxy = 'proxy',
-
- /**
- * @description `new Promise(() => void 0)`
- */
- Promise = 'promise',
-
- /**
- * @description `{ then: () => void 0 }`
- */
- PromiseLike = 'promiseLike',
-
- /**
- * @description `new Date()`
- */
- Date = 'date',
-
- /**
- * @description `new Error()`
- */
- Error = 'error',
-
- /**
- * @description `class Foo {}`
- */
- Class = 'class',
-
- /**
- * @description `new Foo()` where `class Foo {}`
- */
- ClassInstance = 'classInstance',
-
- /**
- * @description `new Map([['foo', 'bar']])`
- */
- Map = 'map',
-
- /**
- * @description `new Map()`
- */
- EmptyMap = 'emptyMap',
-
- /**
- * @description `new WeakMap([[{}, 'bar']])`
- */
- WeakMap = 'weakMap',
-
- /**
- * @description `new WeakMap()`
- */
- EmptyWeakMap = 'emptyWeakMap',
-
- /**
- * @description `new Set(['foo'])`
- */
- Set = 'set',
-
- /**
- * @description `new Set()`
- */
- EmptySet = 'emptySet',
-
- /**
- * @description `new WeakSet([{}])`
- */
- WeakSet = 'weakSet',
-
- /**
- * @description `new WeakSet()`
- */
- EmptyWeakSet = 'emptyWeakSet'
-}
diff --git a/src/lib/test/value.ts b/src/lib/test/value.ts
deleted file mode 100644
index cd224d8..0000000
--- a/src/lib/test/value.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import { ValueType } from './type'
-
-type ValueFactory = () => unknown
-
-const generators = {
- [ValueType.True]: () => true,
- [ValueType.False]: () => false,
- [ValueType.Null]: () => null,
- [ValueType.Undefined]: () => undefined,
- [ValueType.PositiveNumber]: () => 1,
- [ValueType.PositiveInfinity]: () => Infinity,
- [ValueType.Zero]: () => 0,
- [ValueType.NegativeNumber]: () => -1,
- [ValueType.NegativeInfinity]: () => -Infinity,
- [ValueType.PositiveBigInt]: () => BigInt(1),
- [ValueType.NegativeBigInt]: () => BigInt(-1),
- [ValueType.NaN]: () => NaN,
- [ValueType.String]: () => 'foo',
- [ValueType.EmptyString]: () => '',
- [ValueType.Array]: () => [1, 2, 3],
- [ValueType.EmptyArray]: () => [],
- [ValueType.BlankArray]: () => Array(3),
- [ValueType.ArrayLike]: () => ({ length: 3 }),
- [ValueType.ArrayBuffer]: () => new ArrayBuffer(8),
- [ValueType.Object]: () => ({ foo: 'bar' }),
- [ValueType.EmptyObject]: () => ({}),
- [ValueType.RecursiveObject]: () => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const obj: any = {}
- obj.foo = obj
- return obj as {}
- },
- [ValueType.Proxy]: () => new Proxy({}, {}),
- [ValueType.Promise]: () => new Promise(() => void 0),
- [ValueType.PromiseLike]: () => ({ then: () => void 0 }),
- [ValueType.Date]: () => new Date(),
- [ValueType.Error]: () => new Error(),
- [ValueType.Class]: () => class Foo {},
- [ValueType.ClassInstance]: () => new (class Foo {})(),
- [ValueType.Map]: () => new Map([['foo', 'bar']]),
- [ValueType.EmptyMap]: () => new Map(),
- [ValueType.WeakMap]: () => new WeakMap([[{}, 'bar']]),
- [ValueType.EmptyWeakMap]: () => new WeakMap(),
- [ValueType.Set]: () => new Set([1, 2, 3]),
- [ValueType.EmptySet]: () => new Set(),
- [ValueType.WeakSet]: () => new WeakSet([{}, {}]),
- [ValueType.EmptyWeakSet]: () => new WeakSet(),
- [ValueType.Function]: () => () => void 0,
- [ValueType.AsyncFunction]: () => async () => void 0,
- [ValueType.GeneratorFunction]: () =>
- function* () {
- yield 1
- },
- [ValueType.AsyncGeneratorFunction]: () =>
- async function* () {
- yield 1
- },
- [ValueType.Symbol]: () => Symbol('foo')
-} as const satisfies Record>
-
-Object.freeze(generators)
-
-export function allTypes(): ValueType[] {
- return Object.values(ValueType)
-}
-
-export function getGenerator(type: ValueType): () => unknown {
- return generators[type]
-}
-
-export interface TestOption {
- negative?: boolean
-}
diff --git a/src/lib/type.ts b/src/lib/type.ts
deleted file mode 100644
index 1e2b656..0000000
--- a/src/lib/type.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-/**
- * @description error message factory receives the target value as the first argument
- */
-export type TypeErrorMessage = string | ((target: unknown) => string)
-
-type Branded = {
- [_ in `__branded_${T}`]: never
-}
-
-/**
- * @description type guard
- */
-export interface TypeGuard extends Branded<'type_guard'> {
- (target: unknown): target is U
-}
-
-/**
- * @description inverted type guard
- */
-export interface InvertedTypeGuard extends Branded<'inverted_type_guard'> {
- (target: T | U): target is Exclude
-}
-
-/**
- * @description inverted type guard
- */
-export type Not = InvertedTypeGuard>
-
-/**
- *
- */
-export type GuardedType = T extends TypeGuard
- ? U
- : T extends InvertedTypeGuard
- ? U
- : never
-
-/**
- * @description type assertion.
- */
-export interface TypeAssert extends Branded<'type_assert'> {
- (target: unknown, message?: TypeErrorMessage): asserts target is T
-}
-
-/**
- * @description assert function. but it does not assert types.
- */
-export interface VoidAssert extends Branded<'void_assert'> {
- (target: unknown, message?: TypeErrorMessage): void
-}
-
-/**
- * @description inverted type assertion.
- */
-export interface InvertedTypeAssert extends Branded<'inverted_type_assert'> {
- (target: U | T, message?: TypeErrorMessage): asserts target is Exclude
-}
-
-/**
- *
- */
-export type TypeAssertOf = TypeAssert>
-
-/**
- *
- */
-export type InvertedTypeAssertOf = InvertedTypeAssert>
-
-/**
- * @description type ensure.
- */
-export interface TypeEnsure extends Branded<'type_ensurer'> {
- (target: U, message?: TypeErrorMessage): U extends T ? U : never
-}
-
-/**
- * @description inverted type ensure.
- */
-export interface InvertedTypeEnsure extends Branded<'inverted_type_ensurer'> {
- (target: U | T, message?: TypeErrorMessage): U extends T ? never : U
-}
-
-/**
- *
- */
-export type TypeEnsureOf = TypeEnsure>
-
-/**
- *
- */
-export type InvertedTypeEnsureOf = InvertedTypeEnsure>
-
-/**
- *
- */
-export interface PartialFallback {
- (target: V, fallback: W): V extends U ? U : W
-}
-
-/**
- * @description type fallback.
- */
-export interface TypeFallback extends Branded<'type_fallback'> {
- (target: U, fallback: V): U extends T ? U : V
-}
-
-/**
- * @description inverted type fallback.
- */
-export interface InvertedTypeFallback extends Branded<'inverted_type_fallback'> {
- (target: U, fallback: Exclude): U extends T ? V : U
-}
-
-/**
- *
- */
-export type TypeFallbackOf = TypeFallback>
-
-/**
- *
- */
-export type InvertedTypeFallbackOf = InvertedTypeFallback>
diff --git a/src/lib/types/index.ts b/src/lib/types/index.ts
new file mode 100644
index 0000000..dca7843
--- /dev/null
+++ b/src/lib/types/index.ts
@@ -0,0 +1,2 @@
+export * from './json'
+export * from './type-guards'
diff --git a/src/lib/types/json.ts b/src/lib/types/json.ts
new file mode 100644
index 0000000..43dae2d
--- /dev/null
+++ b/src/lib/types/json.ts
@@ -0,0 +1,7 @@
+export type JsonValue = JsonPrimitive | JsonArray | JsonObject
+
+export type JsonPrimitive = string | number | boolean | null
+
+export type JsonArray = JsonValue[] | readonly JsonValue[]
+
+export type JsonObject = { [Key in string]: JsonValue } & { [Key in string]?: JsonValue | undefined }
diff --git a/src/lib/types/type-guards.ts b/src/lib/types/type-guards.ts
new file mode 100644
index 0000000..972502c
--- /dev/null
+++ b/src/lib/types/type-guards.ts
@@ -0,0 +1,92 @@
+/**
+ * @description error message factory receives the target value as the first argument
+ */
+export type TypeErrorMessage = string | ((target: unknown) => string)
+
+/**
+ * @description type guard
+ */
+export interface TypeGuard {
+ (target: unknown): target is U
+}
+
+/**
+ * @description inverted type guard
+ */
+export interface InvertedTypeGuard {
+ (target: T | U): target is unknown extends T | U ? unknown : Exclude
+}
+
+/**
+ * @description inverted type guard
+ */
+export type Not = InvertedTypeGuard>
+
+/**
+ *
+ */
+export type GuardedType = T extends TypeGuard
+ ? U
+ : T extends InvertedTypeGuard
+ ? U
+ : never
+
+/**
+ * @description type assertion.
+ */
+export interface TypeAssert {
+ (target: unknown, message?: TypeErrorMessage): asserts target is U
+ (target: unknown, message?: TypeErrorMessage): asserts target is T
+}
+
+/**
+ * @description assert function. but it does not assert types.
+ */
+export interface VoidAssert {
+ (target: unknown, message?: TypeErrorMessage): void
+}
+
+/**
+ *
+ */
+export type TypeAssertOf = TypeAssert>
+
+/**
+ * @description type ensure.
+ */
+export interface TypeEnsure {
+ (target: U | V, message?: TypeErrorMessage): unknown extends U
+ ? T
+ : Extract extends never
+ ? T
+ : Extract
+
+ (target: unknown, message?: TypeErrorMessage): unknown extends W
+ ? T
+ : Extract extends never
+ ? T
+ : Extract
+}
+
+/**
+ *
+ */
+export type TypeEnsureOf = TypeEnsure>
+
+/**
+ * @description type fallback.
+ */
+export interface TypeFallback {
+ (target: U, fallback: V):
+ | (unknown extends U ? T : Extract extends never ? T : Extract)
+ | V
+
+ (target: unknown, fallback: X):
+ | (unknown extends X ? T : Extract extends never ? T : Extract)
+ | X
+}
+
+/**
+ *
+ */
+export type TypeFallbackOf = TypeFallback>
diff --git a/src/typeGuards/array/assert.spec-d.ts b/src/typeGuards/array/assert.spec-d.ts
index ca40b04..8ae9e9c 100644
--- a/src/typeGuards/array/assert.spec-d.ts
+++ b/src/typeGuards/array/assert.spec-d.ts
@@ -1,67 +1,66 @@
-/* eslint-disable @typescript-eslint/ban-ts-comment */
-import { test, describe, assertType } from 'vitest'
+import { describe, expectTypeOf, test } from 'vitest'
import { assertArray, assertNotArray } from '.'
describe('isArray type tests', () => {
test('assert definite types.', () => {
- const targetArray = [] as string[] | string
- assertArray(targetArray)
- assertType(targetArray)
+ const target = [] as string[] | string
+ assertArray(target)
+ expectTypeOf(target).toEqualTypeOf()
})
test('assert unknown types', () => {
- const targetUnknown = 'string' as unknown
- assertArray(targetUnknown)
- assertType(targetUnknown)
+ const target = 'string' as unknown
+ assertArray(target)
+ expectTypeOf(target).toEqualTypeOf()
})
test('assert union types', () => {
- const targetUnion = [] as string[] | number[] | string
- assertArray(targetUnion)
- assertType(targetUnion)
+ const target = [] as string[] | number[] | string
+ assertArray(target)
+ expectTypeOf(target).toEqualTypeOf()
})
test('assert union types 2', () => {
- const targetUnion2 = [] as Array | string | number
- assertArray(targetUnion2)
- assertType>(targetUnion2)
+ const target = [] as Array | string | number
+ assertArray(target)
+ expectTypeOf(target).toEqualTypeOf>()
})
test('assert tuple types', () => {
const tuple = ['', 0] as [string, number] | string | number
assertArray(tuple)
- assertType<[string, number]>(tuple)
+ expectTypeOf(tuple).toEqualTypeOf<[string, number]>()
})
})
describe('isNotArray type tests', () => {
test('assert definite types.', () => {
- const targetArray = [] as string[] | string
- assertNotArray(targetArray)
- assertType(targetArray)
+ const target = [] as string[] | string
+ assertNotArray(target)
+ expectTypeOf(target).toEqualTypeOf()
})
test('assert unknown types', () => {
- const targetUnknown = 'string' as unknown
- assertNotArray(targetUnknown)
- assertType(targetUnknown)
+ const target = 'string' as unknown
+ assertNotArray(target)
+ expectTypeOf(target).toEqualTypeOf()
})
test('assert union types', () => {
- const targetUnion = [] as string[] | number[] | string
- assertNotArray(targetUnion)
- assertType(targetUnion)
+ const target = [] as string[] | number[] | string
+ assertNotArray(target)
+ expectTypeOf(target).toEqualTypeOf()
})
test('assert union types 2', () => {
- const targetUnion2 = [] as Array | string | number
- assertNotArray(targetUnion2)
- assertType(targetUnion2)
+ const target = [] as Array | string | number
+ assertNotArray(target)
+ expectTypeOf(target).toEqualTypeOf()
})
test('assert tuple types', () => {
const tuple = ['', 0] as [string, number] | string | number
assertNotArray(tuple)
- assertType(tuple)
+ expectTypeOf(tuple).toEqualTypeOf()
})
})
diff --git a/src/typeGuards/array/ensure.spec-d.ts b/src/typeGuards/array/ensure.spec-d.ts
index 62b7ef2..53a8a52 100644
--- a/src/typeGuards/array/ensure.spec-d.ts
+++ b/src/typeGuards/array/ensure.spec-d.ts
@@ -1,57 +1,66 @@
-/* eslint-disable @typescript-eslint/ban-ts-comment */
-import { test, describe, assertType } from 'vitest'
+import { describe, expectTypeOf, test } from 'vitest'
import { ensureArray, ensureNotArray } from '.'
describe('ensureArray type tests', () => {
test('ensure definite types.', () => {
- const targetArray = [] as string[] | string
- assertType(ensureArray(targetArray))
+ const target = [] as string[] | string
+ const result = ensureArray(target)
+ expectTypeOf(result).toEqualTypeOf()
})
test('ensure unknown types', () => {
- const targetUnknown = 'string' as unknown
- assertType(ensureArray(targetUnknown))
+ const target = 'string' as unknown
+ const result = ensureArray(target)
+ expectTypeOf(result).toEqualTypeOf()
})
test('ensure union types', () => {
- const targetUnion = [] as string[] | number[] | string
- assertType(ensureArray(targetUnion))
+ const target = [] as string[] | number[] | string
+ const result = ensureArray(target)
+ expectTypeOf(result).toEqualTypeOf()
})
test('ensure union types 2', () => {
- const targetUnion2 = [] as Array | string | number
- assertType>(ensureArray(targetUnion2))
+ const target = [] as Array | string | number
+ const result = ensureArray(target)
+ expectTypeOf(result).toEqualTypeOf>()
})
test('ensure tuple types', () => {
const tuple = ['', 0] as [string, number] | string | number
- assertType<[string, number]>(ensureArray(tuple))
+ const result = ensureArray(tuple)
+ expectTypeOf(result).toEqualTypeOf<[string, number]>()
})
})
describe('ensureNotArray type tests', () => {
test('ensure definite types.', () => {
- const targetArray = [] as string[] | string
- assertType(ensureNotArray(targetArray))
+ const target = [] as string[] | string
+ const result = ensureNotArray(target)
+ expectTypeOf(result).toEqualTypeOf()
})
test('ensure unknown types', () => {
- const targetUnknown = 'string' as unknown
- assertType(ensureNotArray(targetUnknown))
+ const target = 'string' as unknown
+ const result = ensureNotArray(target)
+ expectTypeOf(result).toEqualTypeOf()
})
test('ensure union types', () => {
- const targetUnion = [] as string[] | number[] | string
- assertType(ensureNotArray(targetUnion))
+ const target = [] as string[] | number[] | string
+ const result = ensureNotArray(target)
+ expectTypeOf(result).toEqualTypeOf()
})
test('ensure union types 2', () => {
- const targetUnion2 = [] as Array | string | number
- assertType(ensureNotArray(targetUnion2))
+ const target = [] as Array | string | number
+ const result = ensureNotArray(target)
+ expectTypeOf(result).toEqualTypeOf()
})
test('ensure tuple types', () => {
const tuple = ['', 0] as [string, number] | string | number
- assertType(ensureNotArray(tuple))
+ const result = ensureNotArray(tuple)
+ expectTypeOf(result).toEqualTypeOf()
})
})
diff --git a/src/typeGuards/array/fallback.spec-d.ts b/src/typeGuards/array/fallback.spec-d.ts
index 2b807ff..f068341 100644
--- a/src/typeGuards/array/fallback.spec-d.ts
+++ b/src/typeGuards/array/fallback.spec-d.ts
@@ -1,46 +1,54 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
-import { test, describe, assertType } from 'vitest'
+import { describe, expectTypeOf, test } from 'vitest'
import { fallbackArray, fallbackNotArray } from '.'
describe('fallbackArray type tests', () => {
test('fallback definite types.', () => {
- const targetArray = [] as string[] | string
- assertType(fallbackArray(targetArray, ['default']))
+ const target = [] as string[] | string
+ const result = fallbackArray(target, ['default'])
+ expectTypeOf(result).toEqualTypeOf()
})
test('fallback definite types with fallback never array', () => {
- const targetNever = [] as string[]
- assertType(fallbackArray(targetNever, []))
+ const target = [] as string[]
+ const result = fallbackArray(target, [])
+ expectTypeOf(result).toEqualTypeOf()
})
test('fallback definite type with unmatched fallback array', () => {
- const targetArray = [] as string[] | string
- assertType(fallbackArray(targetArray, [0]))
+ const target = [] as string[] | string
+ const result = fallbackArray(target, [0])
+ expectTypeOf(result).toEqualTypeOf()
})
test('fallback unknown types', () => {
- const targetUnknown = 'string' as unknown
- assertType(fallbackArray(targetUnknown, ['default'] as unknown[]))
+ const target = 'string' as unknown
+ const result = fallbackArray(target, ['default'] as unknown[])
+ expectTypeOf(result).toEqualTypeOf()
})
test('fallback unknown types with fallback never array', () => {
- const targetNever = 'string' as unknown
- assertType(fallbackArray(targetNever, []))
+ const target = 'string' as unknown
+ const result = fallbackArray(target, [])
+ expectTypeOf(result).toEqualTypeOf()
})
test('fallback union types', () => {
- const targetUnion = [] as string[] | number[] | string
- assertType(fallbackArray(targetUnion, ['default']))
+ const target = [] as string[] | number[] | string
+ const result = fallbackArray(target, ['default'])
+ expectTypeOf(result).toEqualTypeOf()
})
test('fallback union types 2', () => {
- const targetUnion2 = [] as Array | string | number
- assertType>(fallbackArray(targetUnion2, ['default']))
+ const target = [] as Array | string | number
+ const result = fallbackArray(target, ['default'])
+ expectTypeOf(result).toEqualTypeOf>()
})
test('fallback tuple types', () => {
const tuple = ['', 0] as [string, number] | string | number
- assertType<[string] | [string, number]>(fallbackArray(tuple, ['default']))
+ const result = fallbackArray(tuple, ['default'])
+ expectTypeOf(result).toEqualTypeOf<[string] | [string, number]>()
})
test('uncorrect fallback type', () => {
@@ -51,43 +59,51 @@ describe('fallbackArray type tests', () => {
describe('fallbackNotArray type tests', () => {
test('fallback definite types.', () => {
- const targetArray = [] as string[] | string
- assertType(fallbackNotArray(targetArray, 'default'))
+ const target = [] as string[] | string
+ const result = fallbackNotArray(target, 'default')
+ expectTypeOf(result).toEqualTypeOf()
})
test('fallback definite types with fallback never array', () => {
- const targetNever = [] as string[]
- assertType(fallbackNotArray(targetNever, 'default'))
+ const target = [] as string[]
+ const result = fallbackNotArray(target, 'default')
+ expectTypeOf(result).toEqualTypeOf()
})
test('fallback definite type with unmatched fallback array', () => {
- const targetArray = [] as string[] | string
- assertType(fallbackNotArray(targetArray, 0))
+ const target = [] as string[] | string
+ const result = fallbackNotArray(target, 0)
+ expectTypeOf(result).toEqualTypeOf()
})
test('fallback unknown types with unknown fallback value', () => {
- const targetUnknown = 'string' as unknown
- assertType(fallbackNotArray(targetUnknown, 'default' as unknown))
+ const target = 'string' as unknown
+ const result = fallbackNotArray(target, 'default' as unknown)
+ expectTypeOf(result).toEqualTypeOf()
})
test('fallback unknown types with definite fallback value', () => {
- const targetNever = 'string' as unknown
- assertType(fallbackNotArray(targetNever, 'default'))
+ const target = 'string' as unknown
+ const result = fallbackNotArray(target, 'default')
+ expectTypeOf(result).toEqualTypeOf()
})
test('fallback union types', () => {
- const targetUnion = [] as string[] | number[] | string
- assertType(fallbackNotArray(targetUnion, 'default'))
+ const target = [] as string[] | number[] | string
+ const result = fallbackNotArray(target, 'default')
+ expectTypeOf(result).toEqualTypeOf()
})
test('fallback union types 2', () => {
- const targetUnion2 = [] as Array | string | number
- assertType(fallbackNotArray(targetUnion2, 'default'))
+ const target = [] as Array | string | number
+ const result = fallbackNotArray(target, 'default')
+ expectTypeOf(result).toEqualTypeOf()
})
test('fallback tuple types', () => {
const tuple = ['', 0] as [string, number] | string | number
- assertType(fallbackNotArray(tuple, 'default'))
+ const result = fallbackNotArray(tuple, 'default')
+ expectTypeOf(result).toEqualTypeOf()
})
test('uncorrect fallback type', () => {
diff --git a/src/typeGuards/array/guard.spec-d.ts b/src/typeGuards/array/guard.spec-d.ts
index 389c42b..e5d038f 100644
--- a/src/typeGuards/array/guard.spec-d.ts
+++ b/src/typeGuards/array/guard.spec-d.ts
@@ -1,85 +1,84 @@
-/* eslint-disable @typescript-eslint/ban-ts-comment */
-import { test, describe, assertType } from 'vitest'
+import { describe, expectTypeOf, test } from 'vitest'
import { isArray, isNotArray } from '.'
describe('isArray type tests', () => {
test('guard definite types.', () => {
- const targetArray = [] as string[] | string
- if (isArray(targetArray)) {
- assertType(targetArray)
+ const target = [] as string[] | string
+ if (isArray(target)) {
+ expectTypeOf(target).toEqualTypeOf()
} else {
- assertType(targetArray)
+ expectTypeOf(target).toEqualTypeOf()
}
})
test('guard unknown types', () => {
- const targetUnknown = 'string' as unknown
- if (isArray(targetUnknown)) {
- assertType(targetUnknown)
+ const target = 'string' as unknown
+ if (isArray(target)) {
+ expectTypeOf(target).toEqualTypeOf()
} else {
- assertType(targetUnknown)
+ expectTypeOf(target).toEqualTypeOf()
}
})
test('guard union types', () => {
- const targetUnion = [] as string[] | number[] | string
- if (isArray(targetUnion)) {
- assertType(targetUnion)
+ const target = [] as string[] | number[] | string
+ if (isArray(target)) {
+ expectTypeOf(target).toEqualTypeOf()
}
})
test('guard union types 2', () => {
- const targetUnion2 = [] as Array | string | number
- if (isArray(targetUnion2)) {
- assertType>(targetUnion2)
+ const target = [] as Array | string | number
+ if (isArray(target)) {
+ expectTypeOf(target).toEqualTypeOf>()
}
})
test('guard tuple types', () => {
const tuple = ['', 0] as [string, number] | string | number
if (isArray(tuple)) {
- assertType<[string, number]>(tuple)
+ expectTypeOf(tuple).toEqualTypeOf<[string, number]>()
}
})
})
describe('isNotArray type tests', () => {
test('guard definite types.', () => {
- const targetArray = [] as string[] | string
- if (isNotArray(targetArray)) {
- assertType(targetArray)
+ const target = [] as string[] | string
+ if (isNotArray(target)) {
+ expectTypeOf(target).toEqualTypeOf()
} else {
- assertType(targetArray)
+ expectTypeOf(target).toEqualTypeOf()
}
})
test('guard unknown types', () => {
- const targetUnknown = 'string' as unknown
- if (isNotArray(targetUnknown)) {
- assertType(targetUnknown)
+ const target = 'string' as unknown
+ if (isNotArray(target)) {
+ expectTypeOf(target).toEqualTypeOf()
} else {
- assertType(targetUnknown)
+ expectTypeOf(target).toEqualTypeOf()
}
})
test('guard union types', () => {
- const targetUnion = [] as string[] | number[] | string
- if (isNotArray(targetUnion)) {
- assertType(targetUnion)
+ const target = [] as string[] | number[] | string
+ if (isNotArray(target)) {
+ expectTypeOf(target).toEqualTypeOf()
}
})
test('guard union types 2', () => {
- const targetUnion2 = [] as Array | string | number
- if (isNotArray(targetUnion2)) {
- assertType(targetUnion2)
+ const target = [] as Array | string | number
+ if (isNotArray(target)) {
+ expectTypeOf(target).toEqualTypeOf()
}
})
test('guard tuple types', () => {
const tuple = ['', 0] as [string, number] | string | number
if (isNotArray(tuple)) {
- assertType(tuple)
+ expectTypeOf(tuple).toEqualTypeOf()
}
})
})
diff --git a/src/typeGuards/array/index.spec.ts b/src/typeGuards/array/index.spec.ts
index 105edc0..2cfae73 100644
--- a/src/typeGuards/array/index.spec.ts
+++ b/src/typeGuards/array/index.spec.ts
@@ -1,45 +1,45 @@
-import { describe } from 'vitest'
import expected from 'lodash/isArray.js'
+import { describe } from 'vitest'
import {
- assertNotArray,
assertArray,
- ensureNotArray,
+ assertNotArray,
ensureArray,
- fallbackNotArray,
+ ensureNotArray,
fallbackArray,
+ fallbackNotArray,
isArray,
- isNotArray
+ isNotArray,
} from '.'
-import { testAssert, testEnsure, testFallback, testGuard } from '../../lib/test'
+import { testEquivalentAssert, testEquivalentEnsure, testEquivalentFallback, testEquivalentGuard } from '../../lib-test'
describe('isArray', () => {
- testGuard(isArray, expected)
+ testEquivalentGuard(isArray, expected)
})
describe('isNotArray', () => {
- testGuard(isNotArray, expected, { negative: true })
+ testEquivalentGuard(isNotArray, expected, { negative: true })
})
describe('assertArray', () => {
- testAssert(assertArray, expected)
+ testEquivalentAssert(assertArray, expected)
})
describe('assertNotArray', () => {
- testAssert(assertNotArray, expected, { negative: true })
+ testEquivalentAssert(assertNotArray, expected, { negative: true })
})
describe('ensureArray', () => {
- testEnsure(ensureArray, expected)
+ testEquivalentEnsure(ensureArray, expected)
})
describe('ensureNotArray', () => {
- testEnsure(ensureNotArray, expected, { negative: true })
+ testEquivalentEnsure(ensureNotArray, expected, { negative: true })
})
describe('fallbackArray', () => {
- testFallback(fallbackArray, expected, { fallbackValue: ['fallback'] })
+ testEquivalentFallback(fallbackArray, expected, { fallbackValue: ['fallback'] })
})
describe('fallbackNotArray', () => {
- testFallback(fallbackNotArray, expected, { negative: true, fallbackValue: 'fallback' })
+ testEquivalentFallback(fallbackNotArray, expected, { negative: true, fallbackValue: 'fallback' })
})
diff --git a/src/typeGuards/array/index.ts b/src/typeGuards/array/index.ts
index f8798ae..3e795cc 100644
--- a/src/typeGuards/array/index.ts
+++ b/src/typeGuards/array/index.ts
@@ -1,4 +1,5 @@
-import { createAssertion, createEnsure, createFallback, not } from '../../lib/factory'
+import { createAssertion, createEnsure, createFallback, not } from '../../lib'
+import { errorMessage } from '../../lib'
import {
InvertedTypeAssertOf,
InvertedTypeEnsureOf,
@@ -6,12 +7,12 @@ import {
TypeAssertOf,
TypeEnsureOf,
TypeFallbackOf,
- TypeGuard
-} from '../../lib/type'
-import { errorMessage } from '../../lib/error'
+ TypeGuard,
+} from '../../lib/types'
/**
* Checks if a value is an array.
+ *
* @param target The value to check.
* @returns True if the value is an array, false otherwise.
* @example
@@ -28,6 +29,7 @@ type IsArray = typeof isArray
/**
* Asserts that a value is an array.
+ *
* @param target The value to check.
* @param message (optional) The error message to throw if the value is not an array.
* @throws A TypeError with the given message if the value is not an array.
@@ -43,6 +45,7 @@ export const assertArray: TypeAssertOf = createAssertion(isArray, error
/**
* Ensures that a value is an array.
+ *
* @param target The value to check.
* @param message (optional) The error message to throw if the value is not an array.
* @throws A TypeError with the given message if the value is not an array.
@@ -58,6 +61,7 @@ export const ensureArray: TypeEnsureOf