Narcissistic Project Managers

    @resreq/type-error-decorator
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.6 • Public • Published

    type-error-decorator

    version workflow download JavaScript Style Guide

    TypeError Decorator for JavaScript & TypeScript

    When we make a TypeScript-based library, the compiled .d.ts will only work for TypeScript users, and if we need to add type checking for Vanilla JS users as well, we need to write redundant type of judgements.

    This project provides some decorators that make it easy to add type checking to class.

    Install

    npm i @resreq/type-error-decorator

    or

    yarn add @resreq/type-error-decorator

    Documentation

    Get Started

    Using decorators in class.

    import { TypeClass, TypeMethod, TypeParam } from '@resreq/type-error-decorator'
    
    @TypeClass
    class Http {
      options? = {}
      constructor(@TypeParam('Object',false) options?: any) {
        this.options = options
      }
    
      @TypeMethod
      get(@TypeParam('String') url: any, options?: any) {}
    
      @TypeMethod
      post(@TypeParam('String|URL') url: any, @TypeParam('Object') options: any) {}
    }

    Testing your class, with an incorrect parameter type, will throw a TypeError.

    new Http(1)
    // TypeError: constructor arguments[0] must be Object
    const http = new Http()
    http.get(1)
    // TypeError: get arguments[0] must be String
    const http = new Http()
    http.post(1, {})
    // TypeError: post arguments[0] must be String or URL
    const http = new Http()
    http.post(new URL('https://www.example.com/'))
    // TypeError: post arguments[1] is required

    The decorator uses Symbol.toStringTag internally to compare types, so you can use all the built-in constructor names (Upper Camel Case) to define types.

    For example:

    @TypeParam('BigInt|RegExp|Symbol|Request|Response|...')

    Decorators

    TypeClass

    • Arguments: No

    • Usage:

      The check constructor must have @TypeClass added to the class.

    TypeMethod

    • Arguments: No

    • Usage:

      The check method must have @TypeMethod added to the method.

    TypeParam(type, required = true)

    • Arguments:

      • {string} type
      • {Boolean?} required
    • Usage:

      Add @TypeParam to the parameters of the method to set the type of check.

    License

    This project is licensed under the MIT License - see the LICENSE file for details

    Install

    npm i @resreq/type-error-decorator

    DownloadsWeekly Downloads

    9

    Version

    1.0.6

    License

    MIT

    Unpacked Size

    36 kB

    Total Files

    24

    Last publish

    Collaborators

    • molvqingtai