【问题标题】:Typescript Knockout Validation custom ruleTypescript Knockout Validation 自定义规则
【发布时间】:2017-11-17 15:58:51
【问题描述】:

我想使用 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();
}

在构建时我收到此错误:错误 TS7017 元素隐式具有“任何”类型,因为类型“KnockoutValidationRuleDefinitions”没有索引签名。

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

谢谢

【问题讨论】:

    标签: typescript knockout.js knockout-validation


    【解决方案1】:

    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 接口。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      • 2013-12-26
      • 2020-12-12
      相关资源
      最近更新 更多