Installations
npm install strong-type
Developer Guide
Typescript
No
Module System
ESM
Min. Node Version
>=12.21.0
Node Version
16.4.1
NPM Version
7.18.1
Score
99.7
Supply Chain
100
Quality
76
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (95.34%)
HTML (4.66%)
Love this project? Help keep it running — sponsor us today! 🚀
Developer
RIAEvangelist
Download Statistics
Total Downloads
5,070,688
Last Day
2,127
Last Week
50,757
Last Month
225,605
Last Year
2,068,850
GitHub Statistics
MIT License
9 Stars
62 Commits
4 Watchers
3 Branches
1 Contributors
Updated on Feb 04, 2024
Bundle Size
4.41 kB
Minified
1.22 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.1.0
Package Id
strong-type@1.1.0
Size
8.07 kB
NPM Version
7.18.1
Node Version
16.4.1
Published on
Jul 05, 2021
Total Downloads
Cumulative downloads
Total Downloads
5,070,688
Last Day
-9.1%
2,127
Compared to previous day
Last Week
-15.9%
50,757
Compared to previous week
Last Month
57.6%
225,605
Compared to previous month
Last Year
-2.9%
2,068,850
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dev Dependencies
5
strong-type
Strongly Typed native JS without a hard requirement for transpiling.
What TypeScript should have been. 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, 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 strong-type info : See npm trends and stats for strong-type
npm install --save strong-type
Build Info, GitHub Action CI (linux,windows & Mac) :
What does strong-type do?
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
string-type
is tested using 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 strong-type CDN home : https://cdn-p939v.ondigitalocean.app/strong-type/
Example | strict vs. non-strict
Using strict
and non-strict
modes. By default 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, strong-type
will return false
instead of throwing when the check fails, and will still return true
when it passes.
strict
1import Is from 'strong-type'; 2 3//strict 4const is = new Is; 5const is = new Is(); 6const is = new Is(true); 7 8//throws 9is.string(1); 10 11//union or multiple possible types 12//should not throw 13is.union(1,'string|number'); 14 15//union or multiple possible types 16//should throw 17function check(any){ 18 is.defined(any); 19} 20
non-strict
1import Is from 'strong-type'; 2 3//non-strict 4const is = new Is(false); 5 6//returns false 7is.string(1); 8 9//union or multiple possible types 10//should return true 11is.union(1,'string|number'); 12
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
.
Union | args |
---|---|
is.union | value ,pipe|seperated|type|list |
Most Common Type Methods | args |
---|---|
is.globalThis | value |
is.array | value |
is.bigint | value |
is.boolean | value |
is.date | value |
is.finite | value |
is.generator | value |
is.asyncGenerator | value |
is.infinity | value |
is.map | value |
is.NaN | value |
is.null | value |
is.number | value |
is.object | value |
is.promise | value |
is.regExp | value |
is.set | value |
is.string | value |
is.symbol | value |
is.undefined | value |
is.weakMap | value |
is.weakSet | value |
Function Type Methods | args |
---|---|
is.function | value |
is.asyncFunction | value |
is.generatorFunction | value |
is.asyncGeneratorFunction | value |
Error Type Methods | args |
---|---|
is.error | value |
is.evalError | value |
is.rangeError | value |
is.referenceError | value |
is.syntaxError | value |
is.typeError | value |
is.URIError | value |
Buffer/Typed Array Type Methods | args |
---|---|
is.arrayBuffer | value |
is.dataView | value |
is.sharedArrayBuffer | value |
is.bigInt64Array | value |
is.bigUint64Array | value |
is.float32Array | value |
is.float64Array | value |
is.int8Array | value |
is.int16Array | value |
is.int32Array | value |
is.uint8Array | value |
is.uint8ClampedArray | value |
is.uint16Array | value |
is.uint32Array | value |
Intl Type Methods | args |
---|---|
is.intlDateTimeFormat | value |
is.intlCollator | value |
is.intlDisplayNames | value |
is.intlListFormat | value |
is.intlLocale | value |
is.intlNumberFormat | value |
is.intlPluralRules | value |
is.intlRelativeTimeFormat | value |
Garbage Collection Type Methods | args |
---|---|
is.finalizationRegistry | value |
is.weakRef | value |
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.
Method | args | description |
---|---|---|
is.throw | valueType , expectedType | this will use the valueType and expectedValueType to create and throw a new TypeError |
is.typeCheck | value , type | this 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.instanceCheck | value =new Fake , constructor =FakeCore | The 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.symbolStringCheck | value , type | This 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.compare | value , targetValue , typeName | this 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.defined | value | this will check that a value is not is.undefined any type is valid except undefined . |
is.any | value | this is an alias to is.defined which will allow any type except undefined . |
is.exists | value | this 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
strong-type
is intended to be very simple to use.
1import Is from 'strong-type'; 2 3//strict 4const is = new Is; 5 6function strongTypeRequired(aNumber,aString,anAsyncFunction){ 7 is.number(aNumber); 8 is.string(aString); 9 is.asyncFunction(anAsyncFunction); 10} 11 12function unionStrongTypeRequired(aNumberOrString){ 13 is.union(aNumberOrString,'number|string'); 14} 15 16 17//this will throw because we do not pass an async Function, but rather a normal function. 18strongTypeRequired(1,'a',function(){}) 19 20//these will both pass because we accept both types in a union for the first param. 21unionStrongTypeRequired(1); 22unionStrongTypeRequired('a'); 23 24
browser
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.
1import Is from 'strong-type'; 2 3//strict 4const is = new Is; 5 6//empty generator for this example's sake 7function* myGenFunc(){}; 8const myGen=myGenFunc(); 9 10//we'll show async as well 11async function* myAsyncGenFunc(){} 12const myAsyncGen=myAsyncGenFunc(); 13 14//empty function 15function myFunc(){}; 16 17//will pass and allow contunue 18is.generator(myGen); 19 20/* 21will fail because a generatorFunction is a 22GeneratorFunction, not a Generator 23*/ 24try{ 25 is.generator(myGenFunc); 26}catch(err){ 27 console.log(err); 28} 29 30//will pass and allow contunue 31is.generatorFunction(myGenFunc); 32 33//will fail because a function is not a generatorFunction 34try{ 35 is.generatorFunction(myFunc); 36}catch(err){ 37 console.log(err); 38} 39 40/* 41will fail because this is STRONG-type, a 42generatorFunction is explicitly a GeneratorFunction, 43and not a Function 44*/ 45try{ 46 is.function(myGenFunc); 47}catch(err){ 48 console.log(err); 49} 50 51//will fail because a function is not a generatorFunction 52try{ 53 is.generatorFunction(myFunc); 54}catch(err){ 55 console.log(err); 56} 57 58//will pass and allow contunue 59is.asyncGeneratorFunction(myAsyncGenFunc); 60 61//will pass and allow contunue 62is.asyncGenerator(myAsyncGen); 63 64/* 65will fail becase STRONG-type 66asyncGenerators and generators are explicitly different 67this is the same for generatorFunctions and functions 68*/ 69try{ 70 is.asyncGenerator(myGen); 71}catch(err){ 72 console.log(err); 73} 74 75try{ 76 is.generator(myAsyncGen); 77}catch(err){ 78 console.log(err); 79} 80 81
browser
node
Date example
1import Is from 'strong-type'; 2 3const is = new Is; 4 5//returns true 6is.date(new Date()); 7 8//throws in strict or returns false in non-strict 9is.date(1975); 10
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
.
1import Is from 'strong-type'; 2 3const is = new Is; 4 5//built in JS isNaN 6//returns false 7isNaN(1); 8 9//all return true 10isNaN(NaN); 11isNaN(undefined); 12isNaN('a'); 13 14//strong-type is.NaN all return false in non-strict mode, 15//or throw in default strict mode 16is.NaN(1); 17is.NaN(undefined); 18is.NaN('a'); 19 20//in strong-type only this returns true 21is.NaN(NaN); 22
browser
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. strong-type CDN home : https://cdn-p939v.ondigitalocean.app/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
1//custom class type constructor 2class Pizza{ 3 constructor(topping){ 4 this.eat=true; 5 } 6} 7 8export {default:Pizza, Pizza}
extension
1import Is from 'strong-type'; 2import Pizza from 'my-delicious-pizza'; 3 4class IsMy extends Is{ 5 //custom pizza type 6 pizza(value){ 7 return this.instanceCheck(value,Pizza); 8 } 9} 10 11export={default:IsMy, IsMy};
test
1import IsMy from 'my-delicious-typechecks'; 2import Pizza from 'my-delicious-pizza'; 3 4const is=new IsMy; 5 6//will throw because 42 is not a Pizza Type 7//and 8is.pizza(42) 9
browser
node

No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: licence:0
- Info: FSF or OSI recognized license: MIT License: licence:0
Reason
5 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-c4w7-xm78-47vh
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:27: update your workflow using https://app.stepsecurity.io/secureworkflow/RIAEvangelist/strong-type/node.js.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:29: update your workflow using https://app.stepsecurity.io/secureworkflow/RIAEvangelist/strong-type/node.js.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npm-publish.yml:24: update your workflow using https://app.stepsecurity.io/secureworkflow/RIAEvangelist/strong-type/npm-publish.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npm-publish.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/RIAEvangelist/strong-type/npm-publish.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npm-publish.yml:35: update your workflow using https://app.stepsecurity.io/secureworkflow/RIAEvangelist/strong-type/npm-publish.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npm-publish.yml:36: update your workflow using https://app.stepsecurity.io/secureworkflow/RIAEvangelist/strong-type/npm-publish.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npm-publish.yml:49: update your workflow using https://app.stepsecurity.io/secureworkflow/RIAEvangelist/strong-type/npm-publish.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npm-publish.yml:50: update your workflow using https://app.stepsecurity.io/secureworkflow/RIAEvangelist/strong-type/npm-publish.yml/main?enable=pin
- Info: 0 out of 8 GitHub-owned GitHubAction dependencies pinned
- Info: 4 out of 4 npmCommand dependencies pinned
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
no SAST tool detected
Details
- Warn: no pull requests merged into dev branch
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/node.js.yml:1
- Warn: no topLevel permission defined: .github/workflows/npm-publish.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Score
3.2
/10
Last Scanned on 2025-02-10
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to 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
stronger-typed-streams
NodeJS Streams, but with stronger types
es-toolkit
A state-of-the-art, high-performance JavaScript utility library with a small bundle size and strong type annotations.
strongly-typed-events
Add the power of events to your (TypeScript) projects!