⚠️ It was my learning project and it's no point to continue it. If you are searching for something similar please check class-validator and class-transformer
Runtime type validation for TypeScript with decorators
import { typedec, tString } from "typedec";
@typedec()
class TestClass {
@tString() public foo: string;
constructor(@tString() foo: string) {
this.foo = foo;
}
}
new TestClass(null); // TypeError: 0 must be a string
const t: TestClass = new TestClass("foo");
t.foo = 100; // // TypeError: foo must be a string
t.foo = "baz";
Typedec is created to help you protect your application/module entities by validating types in runtime. It's designed to be easy to use and integrate(or remove) in your application/module.
npm i --save typedec reflect-metadata
-
reflect-metadata
polyfill should be imported only once in your entire application. More details about it here. -
Typedec requires TypeScript >= 2.0 and the
experimentalDecorators
,emitDecoratorMetadata
compilation options in yourtsconfig.json
file.
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
- string
@tString()
- number
@tNumber()
- boolean
@tBoolean()
- symbol
@tSymbol()
- Enum
@tEnum()
- Instance
@tInstance()
MIT License
Copyright (c) 2018 Elmars Kenigs
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.