【发布时间】:2019-12-01 04:35:51
【问题描述】:
想象一个函数 getValidation 接受一些状态和相应的模式来验证状态。一个例子:
type State = {
selectedColor: string
selectedSize: string
selectedOptions?: Record<string, string>
}
type StateSchema = {
selectedColor: {
required: (val: any) => boolean
}
selectedSize: {
required: (val: any) => boolean
}
selectedOptions?: Record<string, { required: (val: any) => boolean }>
}
const state: State = {
selectedColor: '',
selectedSize: 'small',
}
const schema: StateSchema = {
selectedColor: {
required: (val: any) => Boolean(val)
},
selectedSize: {
required: (val: any) => Boolean(val)
}
}
const validation = getValidation(
schema,
state
)
// validation
{
$isValid: false,
$value: {
selectedColor: '',
selectedSize: 'small',
}
selectedColor: {
$isValid: false,
$value: '',
$validations: {
required: false
}
},
selectedSize: {
$isValid: true,
$value: 'small',
$validations: {
required: true
}
},
}
const state2 = {
selectedColor: '',
selectedSize: 'small',
selectedOptions: {
fit: 'tight',
length: ''
}
}
const schema2 = {
selectedColor: {
required: (val: any) => Boolean(val)
},
selectedSize: {
required: (val: any) => Boolean(val)
},
selectedOptions: {
fit: {
required: (val: any) => Boolean(val)
},
length: {
required: (val: any) => Boolean(val)
}
}
}
const validation2 = getValidation(
schema2,
state2
)
// validation2
{
$isValid: false,
$value: {
selectedColor: '',
selectedSize: 'small',
selectedOptions: {
fit: 'tight',
length: ''
}
}
selectedColor: {
$isValid: false,
$value: '',
$validations: {
required: false
}
},
selectedSize: {
$isValid: true,
$value: 'small',
$validations: {
required: true
}
},
selectedOptions: {
$isValid: false,
$value: {
fit: 'tight',
length: ''
},
fit: {
$isValid: true,
$value: 'tight',
$validations: {
required: true
}
},
length: {
$isValid: false,
$value: '',
$validations: {
required: false
}
},
},
}
以上例子的注意事项:
- 状态可以是用户定义的任何对象
- 架构结构必须与状态结构匹配,直到架构定义了一个对象,其中所有键都是验证该状态点的函数。
- 结果验证结构应与状态结构相匹配,并添加一些内容。 $isValid 和 $value 将为状态对象的每个级别添加。如果架构定义了验证器对象,则应将相应的验证器键添加到 $validations 键中。
如何为这种依赖于另一种类型的结构(在本例中为状态)的模式编写泛型类型或接口?
您将如何编写由 getValidation 生成的验证结果的泛型类型或接口,这取决于状态和模式类型的结构?
【问题讨论】:
标签: typescript typescript-typings typescript-generics