【发布时间】:2020-06-10 00:37:41
【问题描述】:
我有这个验证文件
interface Rule {
required?: true;
isNumber?: true;
isDate?: {
format: string;
}
// ... some other rules
// ruleNames: RuleOptions
}
const RuleMap: {
[key in keyof Required<Rule>]: (
value: any,
options: Required<Rule>[key]
) => boolean;
} = {
required: (value) => value != null,
isNumber: (value) => isNumber(value),
isDate: (value, options) => isDate(value, options),
//...otherRules
}
// now I have a fairly strong typed object RuleMap
RuleMap.isDate('foo', { format: "DD/MM/YYYY" }); // no problem
RuleMap.required('foo', { format: "DD/MM/YYYY" }); // throws error
但是当我尝试这样做时
const myRules: Rule = {
isNumber: true
}
(Object.keys(myRules) as (keyof Rule)[]).forEach((ruleName) => {
// Expect this to be working
RuleMap[ruleName](someValue, myRules[ruleName]);
// This throws error
// 'true | { format: string }' is not assignable to type '(true & { format: string })'
});
例如:
指定isDate 时,RuleMap 强制我输入准确的isDate 函数选项。
当循环 Rule 时,我希望打字稿知道我正在将确切的 ruleName 的 ruleOption 传递给函数。
有可能吗?如果是这样,我应该怎么做?
【问题讨论】:
-
这里的问题是打字稿正在工作,它会抛出错误编译,因为你不能在不检查类型的情况下在同一个循环中为不同的规则应用相同的参数。
-
如何让 typescript 知道我通过了正确的规则?事实上我正在通过正确的规则
-
您正在寻找io-ts。
标签: typescript loops types typescript-typings