npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ts-stronger-types

v0.1.8

Published

Runtime checking of types and integrity for Typescript projects

Downloads

13

Readme

ts-stronger-types

Build Status Backers on Open Collective Sponsors on Open Collective codecov npm npm bundle size npm NPM

Allows stronger types emulation for Typescript in runtime by adding checks for actual type. With it you can rely on your Typescript code more in most cases. Throws error if passed type is different from what you expect (like in C# or similar languages), making your Typescript application behaves similar to application written in strong typed language. Current version supports checking primitive types (String, Number) and Objects for type name equality.

If you tried this, please leave some feedback as issue in repo.

Contents

Mission

Typescript gives huge benefit of compilation and static code analysis. But in runtime we still have pure Javascript. As Language itself it serves for its purpose, and it's very fast nowadays. But when we design complicated systems, we need to have better sense of code! Like we do in languages like C# (which obviously has a own drawbacks and complexities). The mission and the most important idea of this project is to make Typescript / Javascript programming more predictable and runtime safer, make it closer to strong typed languages, functioning at the junction of flexibility and type strength. This will allow to rely on the code more, even when you write library which will be used by other projects, and you don't know how.

Installation

    npm install ts-stronger-types --save

this lib will be used in runtime, so add to 'dependencies', NOT 'devDependencies'

you need to have Typescript in your project with enabled decorators

Usage

Function Decorator

In the current version there is @Typed() decorator, applicable for functions. Just apply it to your function as first decorator in the sequence:

    import { Typed } from 'ts-stronger-types';

    @Typed()
    public multiplyChecked(num: number, num2: number): number {
        return  num * num2;
    }

As result, you will keep types checking NOT only during code compilation, but in Runtime as well.

In case of correct runtime values, function is just executed and result is returned.

But when passed arguments have unexpected types, execution will end up with Exception (Error) or log entry if configured. You can emulate this incorrect behavior through any in test scenario:

    const value: any = { v: 3};
    const result = service.multiplyChecked(2, value);
    // TypeError: Argument: [object Object] has type: object different from expected type: number

In this case no error will be thrown, but console.log will push message.

Usage for standalone functions

As you know, decorators are not supported outside of TS classes. Starting from version 0.1.4 there is checked function, which helps to check types in runtime of standalone functions:

    import { checked } from 'ts-stronger-types';

    checked<Number, Number>(doubleNumber, value, Number, Number);

Config

There is the configuration which can turn on / off features of the library.

What can be configured:

export interface TypedOptions {
    enable: boolean;
    throwError: boolean;
    checkArgumentLength: boolean;
}
  • enable / disable all checks
  • enable / disable throwing errors
  • enable / disable checks of argument length

Default - all is true

You can use one of the following options to configure:

Per Function

    import { Typed } from 'ts-stronger-types';

    @Typed({throwError: false, checkArgumentLength: false})
    public multiplyChecked(num: number, num2: number): number {
        return  num * num2;
    }

This setting has the biggest priority.

During Application Startup

    import { TypedConfig } from 'ts-stronger-types';

    TypedConfig.set({
            enable: true,
            throwError: true,
            checkArgumentLength: true,
        });

This setting has the second priority.

With Environment Variables

You can turn on / off the whole feature using environment variable TYPED. Config tries to read and parse value from 'process.env.TYPED', it can have value like 'true', 'yes' or 1 for enabling and 'false', 'no' or 0 for disabling. For example, your .env file can have: TYPED = false

Custom Logger

const customLogger = (message: string) => void {
    // do whatever you want with message
};

TypedConfig.set({ customLogger });

Motivation

The main motivation is to have system which behaves more like strong type language, but can function in Javascript ecosystem. I described it in more details in the article at kononov.space. In russian at the moment, translation will be soon.

What is checked?

Checks in Code of decorator:

  • arguments length
  • type of each argument (should be equal to type of parameter in reflect-metadata)
  • type of return value (should be equal to return type in reflect-metadata)

What Types we can verify?

  • number
  • string
  • date
  • boolean
  • array
  • class

What Types we CANNOT verify?

Due to current limitations of Typescript / Javascript we cannot verify in runtime following types:

  • interfaces. Each interface doesn't have prototype and it's name is undefined in runtime.
  • type of array members. This is due to lack of reflect-metadata for arrays in Typescript. Potentially it can be done in future if TS team bring needed metadata

Performance Overhead

Performance overhead is very minimal. Measurements where taken with console.time.

First Run

|part|foreach|for| |---|---|---| |clean_func|0.113ms|0.080ms| |metadata|0.208ms|0.148ms| |typeof|0.063ms|0.045ms| |foreach|0.303ms|0.163ms| |checked_func|0.785ms|0.515ms|

Second Run

|part|foreach|for| |---|---|---| |clean_func|0.113ms|0.080ms| |metadata|0.012ms|0.031ms| |typeof|0.002ms|0.001ms| |foreach|0.066ms|0.040ms| |checked_func|0.140ms|0.221ms|

Release Notes

  • 0.0.4 - initial code, documentation, tests and @Typed() decorator itself.
  • 0.1.0 - verification of classes, arrays, return types, code refactoring, 64 tests added, settings
  • 0.1.5 - updates and new experimental standalone function check
    • [x] migrated ts-lint => eslint
    • [x] updated all dependent libs to the latest version, including "typescript": "^4.0.5",
    • [x] merged suggested PR with better error messages
    • [x] merged suggested PR with custom logger
    • [x] use setting no-implicit-any
    • [x] use setting no-explicit-any, except tests
    • [x] change Error => TypeError
    • [x] add ability to check types of a standalone function (not in class) - checked function

Plans

  • Add ability to use this decorator for class itself, not just for particular function
  • Maybe some global checks, but not sure would it be possible
  • Please add more suggestions by finding me in twitter @ValentinKononov

Issues

Post issues in github/ts-runtime-checker/issues

Stay in Touch

Thanks!