ts-guard-decorator 🛡
Decorator for running a check before running a method.
Installation
npm install --save ts-guard-decorator
Usage
Decorators are supported in TypeScript or with Babel.
import guard from 'ts-guard-decorator';
class MyClass {
@guard(typeof window !== 'undefined')
myFunc() {
}
}
This is equivalent to writing:
class MyClass {
myFunc() {
if (typeof window === 'undefined') {
return;
}
}
}
Arguments
The guard accepts 2 arguments:
- A boolean expression (i.e. something that evaluates to
true
or false
) indicating whether the method should run. - A optional return value if the method should not run.
function testGuardFunc(arg1, arg2) {
return arg1 === arg2;
}
class TestClass {
@guard(true)
guardTrue() {
return true;
}
@guard(false)
guardFalse() {
return true;
}
@guard(true, 'hello')
guardTrueRetVal() {
return true;
}
@guard(false, 'hello')
guardFalseRetVal() {
return true;
}
@guard(testGuardFunc(1, 1), 'hello')
guardTrueFunc() {
return true;
}
@guard(testGuardFunc(1, 2), 'hello')
guardFalseFunc() {
return true;
}
}