Zorthgo Zorthgo - 1 month ago 27
TypeScript Question

Custom Angular validator in TypeScript

I've created a custom angular form validator in TypeScript. Everything works fine on the browser but typescript is complaining that "Property 'compareTo' does not exist on type 'IModelValidators'" at this line:

ngModel.$validators.compareTo = modelValue => (modelValue === scope.otherModelValue);
Which makes sense, because I am basically creating a new validator called "comparedTo" that doesn't exist and just attaching it to the model. This is totally valid in javascript but since Typescript is strongly typed it didn't like it that much. Does anyone have any idea of how to add my "compareTo" validation to the ngModel.$validators in a typescript safe way? Thanks!

'use strict';

module App.Directives {

export interface ILoZScope extends angular.IScope {
otherModelValue: string;
}

export class CompareToDirective implements angular.IDirective {

// Directive parameters.
public restrict = 'A';
public require = 'ngModel';
public scope = { otherModelValue: '=compareTo' }

// Constructor
public static $inject = ['$window'];
constructor($window) {}

// Link function
public link(scope: ILoZScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes, ngModel: angular.INgModelController) {

ngModel.$validators.compareTo = modelValue => (modelValue === scope.otherModelValue);

scope.$watch('otherModelValue', () => { ngModel.$validate(); });
}

// Creates an instance of the compareToDirective class.
public static factory(): angular.IDirectiveFactory {
const directive = ($window: angular.IWindowService) => new CompareToDirective($window);
directive.$inject = ['$window'];
return directive;
}

}

angular
.module('app')
.directive('compareTo', CompareToDirective.factory());

}

Answer

If you just want to skip the typescript error, just create a custom definitely typed file and add something like this.

interface IModelValidators {
       comparedTo: any;
    }

If you want to get proper intellisense, use something like this in your custom d.ts file.

interface IModelValidators {
           comparedTo: (modelValue: any, viewValue: any) => boolean;
        }
Comments