https://github.com/arkon/ts-guard-decorator
TypeScript decorator for running a check before running a method.
https://github.com/arkon/ts-guard-decorator
decorator typescript typescript-decorators
Last synced: 10 months ago
JSON representation
TypeScript decorator for running a check before running a method.
- Host: GitHub
- URL: https://github.com/arkon/ts-guard-decorator
- Owner: arkon
- License: mit
- Created: 2017-04-11T21:03:48.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2017-04-13T17:51:24.000Z (about 9 years ago)
- Last Synced: 2024-10-29T20:55:31.531Z (over 1 year ago)
- Topics: decorator, typescript, typescript-decorators
- Language: TypeScript
- Size: 11.7 KB
- Stars: 7
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# ts-guard-decorator 🛡
> Decorator for running a check before running a method.
[](https://nodei.co/npm/ts-guard-decorator)
## Installation
```shell
npm install --save ts-guard-decorator
```
## Usage
Decorators are supported in [TypeScript](https://www.typescriptlang.org/docs/handbook/decorators.html) or with [Babel](https://babeljs.io/docs/plugins/transform-decorators/).
```js
import guard from 'ts-guard-decorator';
class MyClass {
// Don't run `myFunc` if `window` doesn't exist
@guard(typeof window !== 'undefined')
myFunc() {
// ...
}
}
```
This is equivalent to writing:
```js
class MyClass {
myFunc() {
if (typeof window === 'undefined') {
return;
}
// ...
}
}
```
### Arguments
The guard accepts 2 arguments:
1. A boolean expression (i.e. something that evaluates to `true` or `false`) indicating whether the method should run.
2. A optional return value if the method should _not_ run.
```js
function testGuardFunc(arg1, arg2) {
return arg1 === arg2;
}
class TestClass {
@guard(true)
guardTrue() {
return true;
} //=> true
@guard(false)
guardFalse() {
return true;
} //=> undefined
@guard(true, 'hello')
guardTrueRetVal() {
return true;
} //=> true
@guard(false, 'hello')
guardFalseRetVal() {
return true;
} //=> "hello"
@guard(testGuardFunc(1, 1), 'hello')
guardTrueFunc() {
return true;
} //=> true
@guard(testGuardFunc(1, 2), 'hello')
guardFalseFunc() {
return true;
} //=> "hello"
}
```