@@ -259,6 +259,74 @@ new A().method(42) === 42; // true
259259new A ().method (' 42' as any ); // will throw error
260260```
261261
262+ ### async and ` Promise ` returning methods
263+ ` AssertType ` can also work correctly with ` async ` methods, returning promise rejected with ` TypeGuardError `
264+
265+ To enable this functionality, you need to emit decorators metadata for your TypeScript project.
266+
267+ ``` json
268+ {
269+ "compilerOptions" : {
270+ "emitDecoratorMetadata" : true
271+ }
272+ }
273+ ```
274+
275+ Then ` AssertType ` will work with async methods and ` Promise ` returning methods automatically.
276+ ``` typescript
277+ import { ValidateClass , AssertType } from ' typescript-is' ;
278+
279+ @ValidateClass ()
280+ class A {
281+ async method(@AssertType ({ async: true }) value : number ) {
282+ // You can safely use value as a number
283+ return value ;
284+ }
285+
286+ methodPromise(@AssertType ({ async: true }) value : number ): Promise <number > {
287+ // You can safely use value as a number
288+ return Promise .resolve (value );
289+ }
290+ }
291+
292+ new A ().method (42 ).then (value => value === 42 /* true */ );
293+ new A ().method (' 42' as any ).catch (error => {
294+ // error will be of TypeGuardError type
295+ })
296+ new A ().methodPromise (' 42' as any ).catch (error => {
297+ // error will be of TypeGuardError type
298+ })
299+ ```
300+
301+ If you want to throw synchronously for some reason, you can override the behaviour using with ` @AssertType({ async: false }) ` :
302+ ``` typescript
303+ import { ValidateClass , AssertType } from ' typescript-is' ;
304+
305+ @ValidateClass ()
306+ class A {
307+ async method(@AssertType ({ async: false }) value : number ) {
308+ // You can safely use value as a number
309+ return value ;
310+ }
311+ }
312+
313+ new A ().method (42 ).then (value => value === 42 /* true */ );
314+ new A ().method (' 42' as any ); // will throw error
315+ ```
316+
317+ If you cannot or don't want to enable decorators metadata, you still make AssertType reject with promise using ` @AssertType({ async: true }) `
318+ ``` typescript
319+ import { ValidateClass , AssertType } from ' typescript-is' ;
320+
321+ @ValidateClass ()
322+ class A {
323+ async method(@AssertType ({ async: true }) value : number ) {
324+ // You can safely use value as a number
325+ return value ;
326+ }
327+ }
328+ ```
329+
262330## Strict equality (` equals ` , ` createEquals ` , ` assertEquals ` , ` createAssertEquals ` )
263331
264332This family of functions check not only whether the passed object is assignable to the specified type, but also checks that the passed object does not contain any more than is necessary. In other words: the type is also "assignable" to the object. This functionality is equivalent to specifying ` disallowSuperfluousObjectProperties ` in the options, the difference is that this will apply only to the specific function call. For example:
0 commit comments