Package Exports
- ts-guard-decorator
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (ts-guard-decorator) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
ts-guard-decorator 🛡
TypeScript decorator for running a check before running a method.
Installation
npm install --save ts-guard-decoratorUsage
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:
class MyClass {
myFunc() {
if (typeof window === 'undefined') {
return;
}
// ...
}
}Options
The guard accepts 2 arguments:
- A boolean expression (i.e. something that evaluates to
trueorfalse) indicating whether the method should run. - A optional return value if the method should not run.
function myGuardFunc(arg1: any, arg2: any): boolean {
return arg1 === arg2;
}
class MyClass {
@guard(true)
myFunc1() {
return true;
} //=> true
@guard(false)
myFunc2() {
return true;
} //=> undefined
@guard(1 === 1)
myFunc3() {
return true;
} //=> true
@guard(1 === 2, 'hello')
myFunc4() {
return true;
} //=> "hello"
@guard(myGuardFunc(1, 1), 'hello')
myFunc5() {
return true;
} //=> true
@guard(myGuardFunc(1, 2), 'hello')
myFunc6() {
return true;
} //=> "hello"
}