@achrinza/strong-type

中文文档
1.1.20发布于 2024/05/28MITES Module零依赖近 30 天下载 7万

allows easy type enforcement for all JS types objects and classes. it is also extensible and provides simple to use type checks for your own custom classes and types

原始使用文档
文档目录12 节
  1. Strongly Typed native JS without a hard requirement for tra…
  2. What does @achrinza/strong-type do?
  3. Testing and Coverage
  4. Example | strict vs. non-strict
  5. Type check methods
  6. Core methods
  7. Example | Basic type checking
  8. Example | Generator type checking
  9. Date example
  10. isNaN() vs is.NaN()
  11. Running the browser and node type support examples
  12. Extending the Is class for your own Types

@achrinza/strong-type

Strongly Typed native JS without a hard requirement for transpiling.

What TypeScript should have been. @achrinza/strong-type will also work in TypeScript.

Type checking module for anywhere javascript can run ES6 modules. This includes node, electron and the browsers. Fully isomorphic. Unlike other solutions like TypeScript, @achrinza/strong-type works natively and does not require transpiling or bundling unless you want to. This make it inclusive of any framework transpiled or not.

npm install --save @achrinza/strong-type

What does @achrinza/strong-type do?

@achrinza/strong-type allows easy type enforcement for all JS types objects and classes. It also supports type unions for multiple types, as well as special types like .any and .defined. It is also extensible and provides simple to use type checks for your own custom classes and types should you want to use them.

It does all this without requiring any additional tooling or transpiling. This leaves you or your organization free to use whatever toolchain or framework you want, or even... to write vanilla native JS.

Testing and Coverage

@achrinza/strong-type is tested using @node-ipc/vanilla-test which is a bare bones testing framework for js that supports ESM, and covered by C8 which is the default coverage tool built into the node runtime. This pair is the most effective and accurate way to test ES6+ modules.

Run the tests and build the coverage files on your local machine by running node-test or see the coverage files on the @achrinza/strong-type CDN home : https://cdn-p939v.ondigitalocean.app/@achrinza/strong-type/

Example | strict vs. non-strict

Using strict and non-strict modes. By default @achrinza/strong-type runs strict and will throw a verbose err you can handle and use if the check fails, or return true if it passes.

To use non-strict mode, simply pass false to the constructor. In this mode, @achrinza/strong-type will return false instead of throwing when the check fails, and will still return true when it passes.

strict

import Is from '@achrinza/strong-type';

//strict
const is = new Is;
const is = new Is();
const is = new Is(true);

//throws
is.string(1);

//union or multiple possible types
//should not throw
is.union(1,'string|number');

//union or multiple possible types
//should throw
function check(any){
    is.defined(any);
}

non-strict

import Is from '@achrinza/strong-type';

//non-strict
const is = new Is(false);

//returns false
is.string(1);

//union or multiple possible types
//should return true
is.union(1,'string|number');

Type check methods

All of these methods take just one arg, the value to check.

Unions can join any of the types supported by Is.

Unionargs
is.unionvalue,pipe|seperated|type|list
Most Common Type Methodsargs
is.globalThisvalue
is.arrayvalue
is.bigintvalue
is.booleanvalue
is.datevalue
is.finitevalue
is.generatorvalue
is.asyncGeneratorvalue
is.infinityvalue
is.mapvalue
is.NaNvalue
is.nullvalue
is.numbervalue
is.objectvalue
is.promisevalue
is.regExpvalue
is.setvalue
is.stringvalue
is.symbolvalue
is.undefinedvalue
is.weakMapvalue
is.weakSetvalue
Function Type Methodsargs
is.functionvalue
is.asyncFunctionvalue
is.generatorFunctionvalue
is.asyncGeneratorFunctionvalue
Error Type Methodsargs
is.errorvalue
is.evalErrorvalue
is.rangeErrorvalue
is.referenceErrorvalue
is.syntaxErrorvalue
is.typeErrorvalue
is.URIErrorvalue
Buffer/Typed Array Type Methodsargs
is.arrayBuffervalue
is.dataViewvalue
is.sharedArrayBuffervalue
is.bigInt64Arrayvalue
is.bigUint64Arrayvalue
is.float32Arrayvalue
is.float64Arrayvalue
is.int8Arrayvalue
is.int16Arrayvalue
is.int32Arrayvalue
is.uint8Arrayvalue
is.uint8ClampedArrayvalue
is.uint16Arrayvalue
is.uint32Arrayvalue
Intl Type Methodsargs
is.intlDateTimeFormatvalue
is.intlCollatorvalue
is.intlDisplayNamesvalue
is.intlListFormatvalue
is.intlLocalevalue
is.intlNumberFormatvalue
is.intlPluralRulesvalue
is.intlRelativeTimeFormatvalue
Garbage Collection Type Methodsargs
is.finalizationRegistryvalue
is.weakRefvalue

Core methods

You can use these to directly check your own types / classes Or extend the Is class to add your own methods in which you use these for checking more types, especially custom types and classes.

Methodargsdescription
is.throwvalueType, expectedTypethis will use the valueType and expectedValueType to create and throw a new TypeError
is.typeCheckvalue, typethis will check the javascript spec types returned from typeof. So the type arg would be a string of 'string', 'boolean', 'number', 'object', 'undefined', 'bigint' etc.
is.instanceCheckvalue=new Fake, constructor=FakeCoreThe core defaults the args to a Fake instance and the FakeCore class. This allows unsupported js spec types to fail as expected with a TypeError instead of a Reference or other Error (see the ./example/web/ example in firefox which is missing some support for Intl classes). This method compares value with the constructor to insure the value is an instanceof the constructor.
is.symbolStringCheckvalue, typeThis can be used to check the Symbol.toStringTag it works on all types, but in the core we only use it to check generator, GeneratorFunction, async function, and async GeneratorFunction as these have no other way to check their type. A generator for example has a type of [object generator] this way. So you pass in an expected generator as value and the string 'generator' as the type, and we handle the rest including lowercasing everything to insure cross browser and platform checking
is.comparevalue, targetValue, typeNamethis will do an explicit compare on the value and targetValue. In the core, we only use this for JS primitives/constants that have no other way to check such as Infinity and globalThis. The type name is the string representation of the class type, or a very explicit error string as the only place this arg is ever used is when the compare results in a throws.
is.definedvaluethis will check that a value is not is.undefined any type is valid except undefined.
is.anyvaluethis is an alias to is.defined which will allow any type except undefined.
is.existsvaluethis is an alias to is.defined to determine if something exists. Very useful for feature testing. The alias was created for simplicity and transparency.

Example | Basic type checking

@achrinza/strong-type is intended to be very simple to use.

import Is from '@achrinza/strong-type';

//strict
const is = new Is;

function strongTypeRequired(aNumber,aString,anAsyncFunction){
    is.number(aNumber);
    is.string(aString);
    is.asyncFunction(anAsyncFunction);
}

function unionStrongTypeRequired(aNumberOrString){
    is.union(aNumberOrString,'number|string');
}


//this will throw because we do not pass an async Function, but rather a normal function.
strongTypeRequired(1,'a',function(){})

//these will both pass because we accept both types in a union for the first param. 
unionStrongTypeRequired(1);
unionStrongTypeRequired('a');


browser

Basic Type Checking Example Web

node

Basic Type Checking Example Node

Example | Generator type checking

Generators are notoriously confusing to type check for many devs. This is why we chose to use them as an example.

import Is from '@achrinza/strong-type';

//strict
const is = new Is;

//empty generator for this example's sake
function* myGenFunc(){};
const myGen=myGenFunc();

//we'll show async as well
async function* myAsyncGenFunc(){}
const myAsyncGen=myAsyncGenFunc();

//empty function
function myFunc(){};

//will pass and allow contunue
is.generator(myGen);

/*
will fail because a generatorFunction is a 
GeneratorFunction, not a Generator
*/
try{
    is.generator(myGenFunc);
}catch(err){
    console.log(err);
}

//will pass and allow contunue
is.generatorFunction(myGenFunc);

//will fail because a function is not a generatorFunction
try{
    is.generatorFunction(myFunc);
}catch(err){
    console.log(err);
}

/*
will fail because this is @achrinza/strong-type, a 
generatorFunction is explicitly a GeneratorFunction,
and not a Function
*/
try{
    is.function(myGenFunc);
}catch(err){
    console.log(err);
}

//will fail because a function is not a generatorFunction
try{
    is.generatorFunction(myFunc);
}catch(err){
    console.log(err);
}

//will pass and allow contunue
is.asyncGeneratorFunction(myAsyncGenFunc);

//will pass and allow contunue
is.asyncGenerator(myAsyncGen);

/*
will fail becase @achrinza/strong-type 
asyncGenerators and generators are explicitly different
this is the same for generatorFunctions and functions
*/
try{
    is.asyncGenerator(myGen);
}catch(err){
    console.log(err);
}

try{
    is.generator(myAsyncGen);
}catch(err){
    console.log(err);
}


browser

Generator Type Checking Example Web

node

Generator Type Checking Example Node

Date example

import Is from '@achrinza/strong-type';

const is = new Is;

//returns true
is.date(new Date()); 

//throws in strict or returns false in non-strict
is.date(1975);

isNaN() vs is.NaN()

Javascripts types are weak by nature, so the built in isNaN() function returns true for anything that not a number, but is.NaN() only returns true if it is explicitly passed NaN.

import Is from '@achrinza/strong-type';

const is = new Is;

//built in JS isNaN
//returns false
isNaN(1);

//all return true
isNaN(NaN);
isNaN(undefined);
isNaN('a'); 

//@achrinza/strong-type is.NaN all return false in non-strict mode,
//or throw in default strict mode
is.NaN(1);
is.NaN(undefined);
is.NaN('a');

//in @achrinza/strong-type only this returns true
is.NaN(NaN);

browser

Date Type Checking Example Web

node

Date Type Checking Example Node

Running the browser and node type support examples

run npm i in the root dir of this module to make sure you get the devDependencies installed.

node example :

npm run nodeExample The whole screen should be green as all of the types are supported in node.

browser examples and support tests

npm start
this will spin up a node-http-server in this modules root on port 8000. The browser examples are in the ./example/web/ folder. You can see them by going to this local address : http://localhost:8000/

Chrome, Opera, and Edge support all the types so all rows will be green.

You will see some red rows in Firefox as it does not yet support all types. The unsupported types will throw type errors when checked/validated.

Digital Ocean Static App

We use the free Digital Ocean Static Apps to host a version of the local server. It is exactly the same as if you ran npm start on your machine. You can also use this like a CDN as it automatically rebuilds from main/master each time the branch is updated. @achrinza/strong-type CDN home : https://cdn-p939v.ondigitalocean.app/@achrinza/strong-type/

Extending the Is class for your own Types

If you are using type checking on your own types in production, its probably wise for yout to just go ahead and extend the module rather than calling the more cumbersome Core Methods many times.

custom Pizza type

//custom class type constructor
class Pizza{
    constructor(topping){
        this.eat=true;
    }
}

export {default:Pizza, Pizza}

extension

import Is from '@achrinza/strong-type';
import Pizza from 'my-delicious-pizza';

class IsMy extends Is{
    //custom pizza type
    pizza(value){
        return this.instanceCheck(value,Pizza);
    }
}

export={default:IsMy, IsMy};

test

import IsMy from 'my-delicious-typechecks';
import Pizza from 'my-delicious-pizza';

const is=new IsMy;

//will throw because 42 is not a Pizza Type
//and 
is.pizza(42)

browser

Pizza Type Checking Example Web

node

Pizza Type Checking Example Node

版本与发布记录

@achrinza/strong-type 共发布 18 个版本,首次发布于 2022/03/25;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.1.20latest2024/05/282 年前
1.1.92024/05/272 年前
0.1.14v0-latest2024/05/272 年前
0.1.132023/10/253 年前
0.1.122023/10/253 年前
1.1.82023/10/253 年前

关于 @achrinza/strong-type 的常见问题

@achrinza/strong-type 是什么?

allows easy type enforcement for all JS types objects and classes. it is also extensible and provides simple to use type checks for your own custom classes and types

如何安装 @achrinza/strong-type?

在项目目录运行 npm install @achrinza/strong-type,或使用 pnpm add / yarn add / bun add。

@achrinza/strong-type 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/achrinza__strong-type 是否存在。

@achrinza/strong-type 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@achrinza/strong-type 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js ^12.21.0 || 14 || 15 || 16 || 17 || 18 || 19 || 20 || 21 || 。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@achrinza/strong-type 可以商用吗?

@achrinza/strong-type 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@achrinza/strong-type 的下载量有多少?

根据 npm 官方下载统计,@achrinza/strong-type 在 2026/10/05 – 2026/11/03 这 30 天内被下载 69,600 次,日均约 2,320 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@achrinza/strong-type 还在维护吗?

最新版本 1.1.20 发布于 2024/05/28(2 年前);至今共发布 18 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/03/25。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。