Gathering detailed insights and metrics for typescript-is
Gathering detailed insights and metrics for typescript-is
Gathering detailed insights and metrics for typescript-is
Gathering detailed insights and metrics for typescript-is
typescript
TypeScript is a language for application scale JavaScript development
is-what
JS type check (TypeScript supported) functions like `isPlainObject() isArray()` etc. A simple & small integration.
@sindresorhus/is
Type check values
@volar/typescript-faster
TypeScript Language Service Completion API is slow when calculate auto-import.
npm install typescript-is
Typescript
Module System
Min. Node Version
Node Version
NPM Version
TypeScript (98.67%)
JavaScript (1.33%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
963 Stars
379 Commits
34 Forks
7 Watchers
5 Branches
19 Contributors
Updated on Jul 08, 2025
Latest Version
0.20.0
Package Id
typescript-is@0.20.0
Unpacked Size
264.47 kB
Size
38.11 kB
File Count
39
NPM Version
7.11.2
Node Version
16.20.0
Published on
Jul 17, 2023
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
3
1
11
1
typescript-is
is deprecated. It still works with TS 4.8 below, but it will not be updated.For TypeScript v4.8+, please use typia instead.
TypeScript transformer that generates run-time type-checks.
1npm install --save typescript-is 2 3# Ensure you have the required dependencies at compile time: 4npm install --save-dev typescript 5 6# If you want to use the decorators, ensure you have reflect-metadata in your dependencies: 7npm install --save reflect-metadata
If you've worked with TypeScript for a while, you know that sometimes you obtain any
or unknown
data that is not type-safe.
You'd then have to write your own function with type predicates that checks the foreign object, and makes sure it is the type that you need.
This library automates writing the type predicate function for you.
At compile time, it inspects the type you want to have checked, and generates a function that can check the type of a wild object at run-time. When the function is invoked, it checks in detail if the given wild object complies with your favorite type.
In particular, you may obtain wild, untyped object, in the following situations:
fetch
call, which returns some JSON object.
You don't know if the JSON object is of the shape you expect.localStorage
that you've stored earlier.
Perhaps in the meantime the string has been manipulated and is no longer giving you the object you expect.In these situations typescript-is
can come to your rescue.
NOTE this package aims to generate type predicates for any serializable JavaScript object. Please check What it won't do for details.
This package exposes a TypeScript transformer factory at typescript-is/lib/transformer-inline/transformer
As there currently is no way to configure the TypeScript compiler to use a transformer without using it programatically, the recommended way is to compile with ttypescript.
This is basically a wrapper around the TypeScript compiler that injects transformers configured in your tsconfig.json
.
(please vote here to support transformers out-of-the-box: https://github.com/Microsoft/TypeScript/issues/14419)
First install ttypescript
:
1npm install --save-dev ttypescript
Then make sure your tsconfig.json
is configured to use the typescript-is
transformer:
1{ 2 "compilerOptions": { 3 "plugins": [ 4 { "transform": "typescript-is/lib/transform-inline/transformer" } 5 ] 6 } 7}
Now compile using ttypescript
:
1npx ttsc
ts-node
, webpack
, Rollup
Please check the README of ttypescript for information on how to use it in combination with ts-node
, webpack
, and Rollup
.
Note: This will not work if ts-loader
is configured with transpileOnly: true
.
webpack + ts-loader
without ttypescript
If you are using ts-loader
in a webpack
project, you can use getCustomTransformers as suggested in #54.
This means you don't need to use ttypescript
or write a custom compilation script.
Example:
1const typescriptIsTransformer = require('typescript-is/lib/transform-inline/transformer').default 2 3module.exports = { 4 // I am hiding the rest of the webpack config 5 module: { 6 rules: [ 7 { 8 test: /\.ts$/, 9 exclude: /node_modules/, 10 loader: 'ts-loader', 11 options: { 12 getCustomTransformers: program => ({ 13 before: [typescriptIsTransformer(program)] 14 }) 15 } 16 } 17 ] 18 } 19};
Note: This will not work if ts-loader
is configured with transpileOnly: true
.
There are some options to configure the transformer.
Property | Description |
---|---|
shortCircuit | Boolean (default false ). If true , all type guards will return true , i.e. no validation takes place. Can be used for example in production deployments where doing a lot of validation can cost too much CPU. |
ignoreClasses | Boolean (default: false ). If true , when the transformer encounters a class (except for Date ), it will ignore it and simply return true . If false , an error is generated at compile time. |
ignoreMethods | Boolean (default: false ). If true , when the transformer encounters a method, it will ignore it and simply return true . If false , an error is generated at compile time. |
ignoreFunctions (deprecated, use functionBehavior instead) | Boolean (default: false ). If true , when the transformer encounters a function, it will ignore it and simply return true . If false , an error is generated at compile time. |
functionBehavior | One of error , ignore , or basic (default: error ). Determines the behavior of transformer when encountering a function. error will cause a compile-time error, ignore will cause the validation function to always return true , and basic will do a simple function-type-check. Overrides ignoreFunctions . |
disallowSuperfluousObjectProperties | Boolean (default: false ). If true , objects are checked for having superfluous properties and will cause the validation to fail if they do. If false , no check for superfluous properties is made. |
transformNonNullExpressions | Boolean (default: false ). If true , non-null expressions (eg. foo!.bar ) are checked to not be null or undefined |
emitDetailedErrors | Boolean or auto (default: auto ). The generated validation functions can return detailed error messages, pointing out where and why validation failed. These messages are used by assertType<T>() , but are ignored by is<T>() . If false , validation functions return empty error messages, decreasing code size. auto will generate detailed error messages for assertions, but not for type checks. true will always generate detailed error messages, matching the behaviour of version 0.18.3 and older. |
If you are using ttypescript
, you can include the options in your tsconfig.json
:
1{ 2 "compilerOptions": { 3 "plugins": [ 4 { 5 "transform": "typescript-is/lib/transform-inline/transformer", 6 "shortCircuit": true, 7 "ignoreClasses": true, 8 "ignoreMethods": true, 9 "functionBehavior": "ignore", 10 "disallowSuperfluousObjectProperties": true, 11 "transformNonNullExpressions": true, 12 "emitDetailedErrors": "auto" 13 } 14 ] 15 } 16}
Before using, please make sure you've completed configuring the transformer.
In your TypeScript code, you can now import and use the type-check function is
(or createIs
), or the type assertion function assertType
(or createAssertType
).
is
and createIs
)For example, you can check if something is a string
or number
and use it as such, without the compiler complaining:
1import { is } from 'typescript-is'; 2 3const wildString: any = 'a string, but nobody knows at compile time, because it is cast to `any`'; 4 5if (is<string>(wildString)) { // returns true 6 // wildString can be used as string! 7} else { 8 // never gets to this branch 9} 10 11if (is<number>(wildString)) { // returns false 12 // never gets to this branch 13} else { 14 // Now you know that wildString is not a number! 15}
You can also check your own interfaces:
1import { is } from 'typescript-is'; 2 3interface MyInterface { 4 someObject: string; 5 without: string; 6} 7 8const foreignObject: any = { someObject: 'obtained from the wild', without: 'type safety' }; 9 10if (is<MyInterface>(foreignObject)) { // returns true 11 const someObject = foreignObject.someObject; // type: string 12 const without = foreignObject.without; // type: string 13}
assertType
and createAssertType
)Or use the assertType
function to directly use the object:
1import { assertType } from 'typescript-is'; 2 3const object: any = 42; 4assertType<number>(object).toFixed(2); // "42.00" 5 6try { 7 const asString = assertType<string>(object); // throws error: object is not a string 8 asString.toUpperCasse(); // never gets here 9} catch (error) { 10 // ... 11}
ValidateClass
and AssertType
)You can also use the decorators to automate validation in class methods. To enable this functionality, you should make sure that experimental decorators are enabled for your TypeScript project.
1{ 2 "compilerOptions": { 3 "experimentalDecorators": true 4 } 5}
You should also make sure the peer dependency reflect-metadata is installed.
1npm install --save reflect-metadata
You can then use the decorators:
1import { ValidateClass, AssertType } from 'typescript-is'; 2 3@ValidateClass() 4class A { 5 method(@AssertType() value: number) { 6 // You can safely use value as a number 7 return value; 8 } 9} 10 11new A().method(42) === 42; // true 12new A().method('42' as any); // will throw error
Promise
returning methodsAssertType
can also work correctly with async
methods, returning promise rejected with TypeGuardError
To enable this functionality, you need to emit decorators metadata for your TypeScript project.
1{ 2 "compilerOptions": { 3 "emitDecoratorMetadata": true 4 } 5}
Then AssertType
will work with async methods and Promise
returning methods automatically.
1import { ValidateClass, AssertType } from 'typescript-is'; 2 3@ValidateClass() 4class A { 5 async method(@AssertType({ async: true }) value: number) { 6 // You can safely use value as a number 7 return value; 8 } 9 10 methodPromise(@AssertType({ async: true }) value: number): Promise<number> { 11 // You can safely use value as a number 12 return Promise.resolve(value); 13 } 14} 15 16new A().method(42).then(value => value === 42 /* true */); 17new A().method('42' as any).catch(error => { 18 // error will be of TypeGuardError type 19}) 20new A().methodPromise('42' as any).catch(error => { 21 // error will be of TypeGuardError type 22})
If you want to throw synchronously for some reason, you can override the behaviour using with @AssertType({ async: false })
:
1import { ValidateClass, AssertType } from 'typescript-is'; 2 3@ValidateClass() 4class A { 5 async method(@AssertType({ async: false }) value: number) { 6 // You can safely use value as a number 7 return value; 8 } 9} 10 11new A().method(42).then(value => value === 42 /* true */); 12new A().method('42' as any); // will throw error
If you cannot or don't want to enable decorators metadata, you still make AssertType reject with promise using @AssertType({ async: true })
1import { ValidateClass, AssertType } from 'typescript-is'; 2 3@ValidateClass() 4class A { 5 async method(@AssertType({ async: true }) value: number) { 6 // You can safely use value as a number 7 return value; 8 } 9}
equals
, createEquals
, assertEquals
, createAssertEquals
)This family of functions check not only whether the passed object is assignable to the specified type, but also checks that the passed object does not contain any more than is necessary. In other words: the type is also "assignable" to the object. This functionality is equivalent to specifying disallowSuperfluousObjectProperties
in the options, the difference is that this will apply only to the specific function call. For example:
1import { equals } from 'typescript-is'; 2 3interface X { 4 x: string; 5} 6 7equals<X>({}); // false, because `x` is missing 8equals<X>({ x: 'value' }); // true 9equals<X>({ x: 'value', y: 'another value' }); // false, because `y` is superfluous
To see the declarations of the functions and more examples, please check out index.d.ts.
For many more examples, please check out the files in the test/ folder. There you can find all the different types that are tested for.
Date
). Instead, you are encouraged to use the native instanceof
operator. For example:1import { is } from 'typescript-is'; 2 3class MyClass { 4 // ... 5} 6 7const instance: any = new MyClass(); 8is<MyClass>(instance); // error -> classes are not supported. 9 10// Instead, use instanceof: 11if (instance instanceof MyClass) { 12 // ... 13}
is
function. For example:1import { is } from 'typescript-is'; 2 3function magicalTypeChecker<T>(object: any): object is T { 4 return is<T>(object); // error -> type `T` is not bound. 5}
If you stumble upon anything else that is not yet supported, please open an issue or submit a PR. 😉
Features that are planned:
assertOrReject<Type>(object)
will either resolve(object)
or reject(error)
.false || "key" === "key"
can be simplified. Might be more interesting to publish a different library that can transform a TypeScript AST, and then use it here, or use an existing one. Might be out of scope, as there are plenty of minifiers/uglifiers/manglers out there already.1git clone https://github.com/woutervh-/typescript-is.git 2cd typescript-is/ 3npm install 4 5# Building 6npm run build 7 8# Testing 9npm run test
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 7/17 approved changesets -- score normalized to 4
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
18 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-07-07
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 More