2017-06-15 262 views
1

我想使用Typescript为Knockout-Validation库(https://github.com/Knockout-Contrib/Knockout-Validation)编写自定义规则。我有一个的.ts文件,我想了这个代码:Typescript敲除验证自定义规则

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添加新的自定义验证程序的正确方法是什么?

感谢

回答

2

最有可能与type definitions的问题,它没有一个索引添加自定义的验证。你可以在你的代码临时增加的KnockoutValidationRuleDefinitions接口:

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

或明确投ko.validation.rulesany沉默编译:

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

如果你想要这个固定的类型定义本身就可以提高一PR反对DefinitelyTyped reporitory,并将索引器添加到KnockoutValidationRuleDefinitions接口。