Typescript Knockout Validation 自定义规则

Typescript Knockout Validation custom rule

我想使用 Typescript 为 Knockout-Validation 库 (https://github.com/Knockout-Contrib/Knockout-Validation) 编写自定义规则。我有一个 .ts 文件,我正在尝试输出这段代码:

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();
}

在构建时我收到此错误:Error TS7017 Element implicitly has an 'any' type because type 'KnockoutValidationRuleDefinitions' has no index signature.

使用 Typescript 添加新的自定义验证器的正确方法是什么?

谢谢

最有可能是 type definitions 没有索引器来添加自定义验证的问题。您可以在代码中临时扩充 KnockoutValidationRuleDefinitions 接口:

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

或显式将 ko.validation.rules 转换为 any 以使编译器静音:

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

如果您希望在类型定义本身中修复此问题,您可以针对 DefinitelyTyped reporitory 提出 PR,并将索引器添加到 KnockoutValidationRuleDefinitions 接口。