1
votes

I want to write a custom rule for Knockout-Validation library (https://github.com/Knockout-Contrib/Knockout-Validation) using Typescript. I have a .ts file and i'm trying to out this code:

export function enableCustomValidators() {
    ko.validation.rules["myRule"] = {
        validator: function (val: string, otherVal: string) {
            return val === otherVal;
    },
    message: 'The field must equal {0}',
}

    ko.validation.registerExtenders();
}

At build time I am receiving this error: Error TS7017 Element implicitly has an 'any' type because type 'KnockoutValidationRuleDefinitions' has no index signature.

What's the correct way to add a new custom validator using Typescript?

Thanks

1

1 Answers

2
votes

Most likely an issue with the type definitions which does not have an indexer to add custom validations. You can augment the KnockoutValidationRuleDefinitions interface temporarily in your code:

declare global {
    interface KnockoutValidationRuleDefinitions {
        [customValidationRuleName: string]: KnockoutValidationRuleDefinition
    }
}

Or explicitly cast ko.validation.rules as any to silence the compiler:

(ko.validation.rules as any)["myRule"] = {
    validator: function (val: string, otherVal: string) {
        return val === otherVal;
    },
    message: 'The field must equal {0}',
}

If you want this fixed in the type definitions itself you can raise a PR against the DefinitelyTyped reporitory with the indexer added to the KnockoutValidationRuleDefinitions interface.