我想使用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添加新的自定义验证器的正确方法是什么?
由于
答案 0 :(得分:2)
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.