【发布时间】:2019-08-29 18:23:17
【问题描述】:
我不想创建用于验证对象的通用函数。 我希望它接受以下签名的选项对象:
export interface ValidationOptions<T, K extends keyof T = keyof T> {
validators: Map<K, (value: T[K]) => string | null>
}
我希望能够从 K 映射到接受 T[K] 类型参数的验证器函数数组。我遇到的问题是 T[K] 将解析为 T 中的每个可能值,而不是给定键的特定值。
希望下面的代码可以阐明我的意思。
export interface ValidationOptions<T, K extends keyof T = keyof T> {
validators: Map<K, (value: T[K]) => string | null>
}
function fooValidator(value: string) {
if (value === "foo") {
return "Value can't be foo"
}
return null;
}
function isNotTrueValidator(value: boolean) {
if (!value) {
return "Value must be true"
}
return null;
}
interface ObjectToValidate {
stringy: string;
booly: boolean;
}
//(value: T[K]) => string | null will resolve to value: string | boolean here
//Can i make it resolve to the type for the given property instead?
const options: ValidationOptions<ObjectToValidate> = {
//This results in an error with strictFunctionTypes enabled
validators: new Map([
//How can i
["stringy", fooValidator]
])
}
【问题讨论】:
标签: typescript