TypeError Decorator for JavaScript & TypeScript
npm install @resreq/type-error-decorator   
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.
``shell`
npm i @resreq/type-error-decorator
or
`shell`
yarn add @resreq/type-error-decorator
Using decorators in class.
`js
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.
`js`
new Http(1)
// TypeError: constructor arguments[0] must be Object
`js`
const http = new Http()
http.get(1)
// TypeError: get arguments[0] must be String
`js`
const http = new Http()
http.post(1, {})
// TypeError: post arguments[0] must be String or URL
`js`
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:
`js`
@TypeParam('BigInt|RegExp|Symbol|Request|Response|...')
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.
This project is licensed under the MIT License - see the LICENSE file for details