From 06a8ad28a72c88f0f6949dd55341c1c7a2512f90 Mon Sep 17 00:00:00 2001 From: lazarljubenovic Date: Sat, 7 Sep 2019 20:13:19 +0200 Subject: [PATCH] refactor(forms): use a type guard to get rid of casts (#32541) Use an explicit type guard when checking if a given object is of type AbstractControlOptions, instead of a simple function returning a boolean value. This allows us to remove manual type casting when using this function, relying instead on TypeScript to infer correct types. PR Close #32541 --- packages/forms/src/model.ts | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/packages/forms/src/model.ts b/packages/forms/src/model.ts index 91bb19ddd4..51dcb5937a 100644 --- a/packages/forms/src/model.ts +++ b/packages/forms/src/model.ts @@ -71,11 +71,7 @@ function _find(control: AbstractControl, path: Array|string, deli function coerceToValidator(validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions| null): ValidatorFn|null { - const validator = - (isOptionsObj(validatorOrOpts) ? (validatorOrOpts as AbstractControlOptions).validators : - validatorOrOpts) as ValidatorFn | - ValidatorFn[] | null; - + const validator = isOptionsObj(validatorOrOpts) ? validatorOrOpts.validators : validatorOrOpts; return Array.isArray(validator) ? composeValidators(validator) : validator || null; } @@ -84,10 +80,7 @@ function coerceToAsyncValidator( validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null): AsyncValidatorFn| null { const origAsyncValidator = - (isOptionsObj(validatorOrOpts) ? (validatorOrOpts as AbstractControlOptions).asyncValidators : - asyncValidator) as AsyncValidatorFn | - AsyncValidatorFn | null; - + isOptionsObj(validatorOrOpts) ? validatorOrOpts.asyncValidators : asyncValidator; return Array.isArray(origAsyncValidator) ? composeAsyncValidators(origAsyncValidator) : origAsyncValidator || null; } @@ -119,7 +112,7 @@ export interface AbstractControlOptions { function isOptionsObj(validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions| - null): boolean { + null): validatorOrOpts is AbstractControlOptions { return validatorOrOpts != null && !Array.isArray(validatorOrOpts) && typeof validatorOrOpts === 'object'; } @@ -914,8 +907,8 @@ export abstract class AbstractControl { /** @internal */ _setUpdateStrategy(opts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null): void { - if (isOptionsObj(opts) && (opts as AbstractControlOptions).updateOn != null) { - this._updateOn = (opts as AbstractControlOptions).updateOn!; + if (isOptionsObj(opts) && opts.updateOn != null) { + this._updateOn = opts.updateOn!; } }