New:Socket for Asana Is Now Available.Learn more
Get Started

strong-type

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

strong-type

Dependency-free native ESM type enforcement for JavaScript values, objects, classes, browsers, and Node.

Source
npmnpm
Version
2.0.0
Version published
Weekly downloads
66K
-26.76%
Maintainers
1
Weekly downloads
 
Created
Source

strong-type JavaScript values passing through a native type-validation gate

strong-type

Overview · Validator reference · Tests & coverage · Playground

npm version Node support CI license dependencies

Native type enforcement for JavaScript. strong-type runs as the same untransformed ES module in browsers and Node. Strict checks throw a useful TypeError; non-strict checks return a boolean.

Native by design

PropertyGuaranteeWhat it means
Module formatNative ESMThe checked-in JavaScript is what the runtime executes.
Runtime dependenciesNoneNo third-party production packages.
Development dependenciesNoneTests and the local docs server use Node built-ins.
BundlerNot requiredBrowser and Node imports work directly.
TranspilerNot requiredNo generated CommonJS or compatibility copy.
Default entry pointIsomorphicindex.js contains no node:* imports.
Node supportExplicit adapterstrong-type/node adds Node-only precision checks.
ExtensibilityExported Is classCustom validators work directly and in unions.

Install

npm install strong-type
ImportRuntimeContentsBuild required
strong-typeBrowser + NodeAll isomorphic and guarded host validatorsNo
strong-type/index.jsBrowser + NodeCompatibility path to the same coreNo
strong-type/nodeNodeCore plus Node built-ins and exact util.types checksNo
strong-type/node.jsNodeCompatibility path to the Node adapterNo

Quick start

import Is from 'strong-type';

const is=new Is;
const weakIs=new Is(false);

is.string('strong-type');        // true
weakIs.number('42');             // false
is.union(new Map,'map|set');     // true

is.number('42');                 // throws TypeError

Strict and non-strict modes

ModeCreatePassing checkFailing checkBest use
Strictnew Is or new Is(true)Returns trueThrows TypeErrorContracts and enforcement
Non-strictnew Is(false)Returns trueReturns falseBranching and type discovery

Every advertised method exists in every runtime. When a guarded platform capability is unavailable, strict mode throws TypeError and non-strict mode returns false. Missing APIs never leak a ReferenceError.

Validator reference

The default isomorphic entry exposes 183 validators. The Node adapter adds 18, for 201 documented validators total. The website reference gives every method its own searchable row with an example, edge case, and runtime label.

Values, primitives, and numbers

MethodsWhat passesImportant detail
defined, any, existsAnything except undefinednull is defined.
nullExactly nullNo loose comparison; undefined fails.
nullishnull or undefinedOther falsy values fail.
undefinedExactly undefinednull fails.
booleanPrimitive booleansBoxed Boolean objects fail.
bigInt, bigintPrimitive bigint valuesbigint is the lowercase alias.
numberPrimitive numbersIncludes NaN and infinities.
finite, finiteNumberFinite primitive numbersStrings, null, and BigInt are not coerced.
integerInteger primitive numbersNaN and infinities fail.
safeIntegerSafe integer primitive numbersUses Number.isSafeInteger.
NaN, nanExactly numeric NaNNo string coercion.
infinity, positiveInfinityExactly positive Infinityinfinity keeps its positive-only compatibility meaning.
negativeInfinityExactly negative InfinityPositive Infinity fails.
infiniteEither infinityFinite numbers fail.
negativeZeroExactly -0Uses Object.is; +0 fails.
stringPrimitive stringsBoxed String objects fail.
symbolPrimitive symbolsBoxed Symbol objects fail.
primitivenull or any non-object, non-function valueBoxed primitives and functions fail.
globalThisExactly the current globalThisHost aliases are not substituted.
atomics, json, math, reflectTheir exact global namespacesIdentity checks, not lookalike objects.
rawJSONValues created by JSON.rawJSONGuarded until JSON.isRawJSON exists.

Objects and collections

MethodsWhat passesImportant detail
arrayArrays from any realmUses Array.isArray.
dateDate objects from any realmInvalid dates still pass.
validDateDates with a valid time valueInvalid Date fails.
map, weakMap, set, weakSetTheir matching collection brandsNative internal-slot probes work across realms.
objectValues where typeof value === 'object'Compatibility behavior: null passes.
nonNullObjectNon-null object valuesUse this for the ordinary meaning of object.
plainObjectPlain records, including null-prototype recordsArrays and class instances fail.
nullPrototypeObjectObjects with an exact null prototypeOrdinary object literals fail.
argumentsObjectFunction arguments objectsArrays fail.
promisePromise instances in the current realmStructural thenables have a separate check.
thenableObjects or functions with a callable thenIt never invokes then.
regExp, regexpRegExp objects from any realmregexp is the lowercase-p alias.

Boxed primitives

MethodWhat passesPrimitive near miss
boxedPrimitiveAny boxed Boolean, Number, BigInt, String, or Symbol1
booleanObjectObject(true)true
numberObjectObject(1)1
bigIntObjectObject(1n)1n
stringObjectObject('type')'type'
symbolObjectObject(Symbol('type'))Symbol('type')

Functions and protocols

MethodsWhat passesImportant detail
function, callableAnything whose typeof is functionIncludes async and generator functions.
asyncFunctionAsync functionsOrdinary functions fail.
generatorFunctionGenerator functionsGenerator objects use generator.
asyncGeneratorFunctionAsync generator functionsObjects use asyncGenerator.
generator, asyncGeneratorTheir matching generator iterator objectsFunction values fail.
iteratorValues with a callable nextStructural by design.
asyncIteratorValues with next and Symbol.asyncIteratorStructural by design.
iterable, asyncIterableValues with the matching symbol methodNull-safe and getter-safe.

Errors

MethodsWhat passesRuntime
errorError instancesShared
aggregateErrorAggregateError instancesGuarded standard
evalErrorEvalError instancesShared
rangeErrorRangeError instancesShared
referenceErrorReferenceError instancesShared
syntaxErrorSyntaxError instancesShared
typeErrorTypeError instancesShared
URIError, uriErrorURIError instancesShared; lowercase alias included
suppressedErrorSuppressedError instancesGuarded standard

Typed arrays and buffers

MethodsWhat passesImportant detail
typedArrayAny typed arrayExcludes DataView.
arrayBufferViewAny typed array or DataViewUses ArrayBuffer.isView.
bigInt64Array, bigUint64ArrayMatching BigInt typed arraysExact brand.
float16ArrayFloat16ArrayGuarded on older runtimes.
float32Array, float64ArrayMatching float typed arraysExact brand.
int8Array, int16Array, int32ArrayMatching signed integer typed arraysExact brand.
uint8Array, uint8ClampedArray, uint16Array, uint32ArrayMatching unsigned integer typed arraysA Node Buffer is also a Uint8Array.
arrayBufferArrayBufferCross-realm native slot probe.
sharedArrayBufferSharedArrayBufferGuarded where shared memory is absent.
anyArrayBufferEither buffer kindViews fail.
dataViewDataViewTyped arrays fail.
resizableArrayBufferResizable ArrayBuffer valuesFixed buffers fail.
growableSharedArrayBufferGrowable SharedArrayBuffer valuesFixed shared buffers fail.
detachedArrayBufferTransferred/detached ArrayBuffer valuesThe fallback probe is non-destructive.

Intl

MethodsWhat passesAvailability
intlDateTimeFormatIntl.DateTimeFormatShared
intlCollatorIntl.CollatorShared
intlDisplayNamesIntl.DisplayNamesGuarded
intlListFormatIntl.ListFormatGuarded
intlLocaleIntl.LocaleShared
intlNumberFormatIntl.NumberFormatShared
intlPluralRulesIntl.PluralRulesShared
intlRelativeTimeFormatIntl.RelativeTimeFormatGuarded
intlSegmenterIntl.SegmenterGuarded
intlSegmentsValues returned by segmenter.segment()Guarded
intlDurationFormatIntl.DurationFormatGuarded

Lifetime, resources, and Temporal

MethodsWhat passesAvailability
finalizationRegistryFinalizationRegistry objectsGuarded standard
weakRefWeakRef objectsGuarded standard
disposableValues with callable Symbol.disposeGuarded structural protocol
asyncDisposableValues with callable Symbol.asyncDisposeGuarded structural protocol
disposableStackDisposableStack objectsGuarded standard
asyncDisposableStackAsyncDisposableStack objectsGuarded standard
temporalDurationTemporal.DurationGuarded standard
temporalInstantTemporal.InstantGuarded standard
temporalPlainDateTemporal.PlainDateGuarded standard
temporalPlainDateTimeTemporal.PlainDateTimeGuarded standard
temporalPlainMonthDayTemporal.PlainMonthDayGuarded standard
temporalPlainTimeTemporal.PlainTimeGuarded standard
temporalPlainYearMonthTemporal.PlainYearMonthGuarded standard
temporalZonedDateTimeTemporal.ZonedDateTimeGuarded standard

Shared Web APIs

These methods are present on every Is instance. The constructor or singleton is resolved through globalThis only when the method is called.

FamilyMethodsWhat passes
URLurl, urlSearchParams, urlPatternMatching URL API objects
TexttextEncoder, textDecoder, textEncoderStream, textDecoderStreamEncoding API objects
DatadomException, blob, file, formData, headers, request, responseMatching Fetch/data objects
CancellationabortController, abortSignalMatching cancellation objects
Eventsevent, eventTarget, customEvent, messageEvent, closeEvent, errorEventMatching event objects
MessagingbroadcastChannel, messageChannel, messagePort, webSocket, eventSourceMatching communication objects
Host valuesnavigator, storageThe current navigator or a Storage object
Readable streamsreadableStream, readableStreamDefaultReader, readableStreamBYOBReader, readableStreamDefaultController, readableByteStreamController, readableStreamBYOBRequestMatching Web Streams objects
Writable streamswritableStream, writableStreamDefaultWriter, writableStreamDefaultControllerMatching Web Streams objects
Transform streamstransformStream, transformStreamDefaultControllerMatching transform objects
QueuingbyteLengthQueuingStrategy, countQueuingStrategyMatching strategy objects
CompressioncompressionStream, decompressionStreamMatching compression objects
Cryptocrypto, subtleCrypto, cryptoKeyCurrent crypto services and keys
Performanceperformance, performanceEntry, performanceMark, performanceMeasure, performanceObserver, performanceObserverEntryList, performanceResourceTimingMatching performance objects
WebAssemblywebAssemblyModule, webAssemblyInstance, webAssemblyMemory, webAssemblyTable, webAssemblyGlobal, webAssemblyTag, webAssemblyException, webAssemblyCompileError, webAssemblyLinkError, webAssemblyRuntimeErrorMatching WebAssembly objects and errors

Core and extension methods

MethodResultPurpose
throw(valueType,expectedType)false or throwsCentral strict/non-strict failure behavior.
check(value,pass,expectedType)true, false, or throwsTurn a predicate into strong-type behavior.
typeCheck(value,type)true, false, or throwsValidate a typeof result.
instanceCheck(value,constructor)true, false, or throwsValidate a custom class or realm-local constructor.
symbolStringCheck(value,type)true, false, or throwsValidate an intrinsic object tag.
compare(value,target,typeName)true, false, or throwsCompare exact identity with Object.is.
globalInstanceCheck(value,type)true, false, or throwsGuard and check a named global constructor.
nestedInstanceCheck(value,container,type)true, false, or throwsGuard and check a constructor inside a namespace.
globalValueCheck(value,type)true, false, or throwsCheck exact identity with a named global value.
nestedValueCheck(value,container,type)true, false, or throwsCheck exact identity with a nested value.
union(value,types)true, false, or throwsAccept one named validator from a pipe string or array.

Unions

is.union('type','string|number');
is.union(42,['string','number']);
BehaviorResult
Whitespace around pipe namesTrimmed
Matching validatorCalled once
Custom subclass validatorSupported
Node adapter validatorSupported through IsNode
Inherited Object method such as toStringRejected
Multi-argument helper methodRejected

Node adapter

import IsNode from 'strong-type/node';

const is=new IsNode;

is.buffer(Buffer.from('type'));
is.proxy(new Proxy({},{}));
is.nodeReadable(process.stdin);

The adapter imports Node built-ins only. It never enters the default browser-safe import graph.

MethodWhat passesImportant detail
bufferNode Buffer valuesA plain Uint8Array fails.
nodeStreamAny classic Node StreamWeb Streams use the shared validators.
nodeReadableNode Readable streamsDuplex and Transform inherit Readable.
nodeWritableNode Writable streamsDuplex and Transform inherit Writable.
nodeDuplexNode Duplex streamsPlain readable or writable streams fail.
nodeTransformNode Transform streamsPassThrough inherits Transform.
nodePassThroughNode PassThrough streamsOther transforms fail.
eventEmitterNode EventEmitter instancesDOM EventTarget fails.
timeoutHandles returned by setTimeoutConstructor is discovered lazily.
immediateHandles returned by setImmediateConstructor is discovered lazily.
keyObjectNode crypto KeyObject valuesWeb CryptoKey uses cryptoKey.
x509CertificateNode X509Certificate objectsRequires a parseable certificate.
proxyProxy valuesExact util.types.isProxy check.
moduleNamespaceObjectResults from import()Exact util.types check.
externalNative external valuesUsually supplied by a native addon.
nativeErrorNative Error valuesIncludes cross-realm errors.
mapIteratorNative Map iteratorsSet iterators fail.
setIteratorNative Set iteratorsMap iterators fail.

Direct browser use without bundling

Use a native import map. Serve the files over HTTP; browsers do not load ES modules reliably from file: URLs.

<script type="importmap">
    {
        "imports": {
            "strong-type": "./node_modules/strong-type/index.js"
        }
    }
</script>

<script type="module">
    import Is from 'strong-type';

    const is=new Is;
    console.log(is.url(new URL('https://example.com')));
</script>

You can also import the source directly in a native module script:

<script type="module">
    import Is from 'https://riaevangelist.github.io/strong-type/index.js';

    const is=new Is;
    console.log(is.string('native ESM'));
</script>

Use your own hosted path instead of the project Pages URL when you want to serve the file yourself. No bundle, transform, runtime shim, or host switch is involved.

Extend strong-type

import Is from 'strong-type';

class Pizza{}

class MyIs extends Is{
    pizza(value){
        return this.instanceCheck(value,Pizza);
    }
}

const is=new MyIs;

is.pizza(new Pizza);
is.union(new Pizza,'pizza|string');
Extension helperUse
this.typeCheck(value,'string')Custom typeof validator
this.instanceCheck(value,Pizza)Custom class validator
this.check(value,predicate,'description')Any custom predicate with standard strict behavior
this.throw(actual,expected)Explicit failure path

Corrected exact behavior

Version 2 removes several coercive edge cases while retaining the original method names.

CheckOld behaviorCurrent behavior
null(undefined)Passed through loose equalityFails
infinity('Infinity')Passed through loose equalityFails
finite('1')Passed through global coercive isFiniteFails
finite(null)Passed through coercionFails
finite(1n)Could leak a native errorReturns false or throws strong-type TypeError
union(value,' string | number ')Did not trim namesWorks
union(value,'toString')Could call an inherited methodRejected
Subclass validators in unionLost by constructing base IsPreserved

Tests and coverage

The main suite runs with Node's built-in node:test. Node 12.21 uses the same registered cases through the small compatibility adapter because node:test did not exist in that release. There is no third-party test runner.

Test suiteResult on Node 24.18.0Covers
Core validators533 passed · 13 guarded skips183 isomorphic validators, strict/non-strict behavior, hostile values, unions, and native brands
Node adapter54 passed18 Node validators, cross-realm behavior, package entry points, streams, timers, crypto, and proxies
Documentation10 passedComplete method tables, local assets, zero dependencies, package paths, and bundle-free playground wiring
Total597 passed · 0 failed · 13 skippedRuntime and documentation contract

A guarded skip means the runtime does not expose that host API. It is a capability result, not an ignored failure.

Coverage uses Node 24's built-in V8 reporter and includes only the two shipped runtime sources.

SourceLinesBranchesFunctions
index.js95.74% · 1102/115191.37% · 286/31399.57% · 229/230
node.js96.80% · 121/12593.75% · 30/3291.30% · 21/23
Total95.85% · 1223/127691.59% · 316/34598.81% · 250/253
MetricCurrentCI floor
Lines95.85%95%
Branches91.59%90%
Functions98.81%95%

Node's native reporter does not publish a statement metric. Test and documentation files are excluded from the percentages. See the full test, coverage, and CI explanation.

Commands

CommandWhat it doesThird-party tooling
npm testRuns core, Node adapter, and documentation checks through node:testNone
npm run test:coreRuns portable validator regression tests through node:testNone
npm run test:nodeRuns Node adapter and cross-realm tests through node:testNone
npm run test:docsChecks reference completeness and site integrity through node:testNone
npm run test:legacyRuns the same registered cases on Node 12.21None
npm run coverageRuns native V8 coverage and enforces the 95/90/95 release floorsNone
npm startServes the docs and playground at http://localhost:8000/None
npm run nodeExampleRuns the Node exampleNone

License

MIT · Roshi _ _

Keywords

strong

FAQs

Package last updated on 15 Aug 2026

Related posts