我有一个检查输入字段有效性的功能。
export const getInputValidity = (inputData:DeepReadonly<InputData> , val:string) => {
const {length} = val
if (inputData.type==="select"){
return val.length<5
}
if (inputData.type==="email"){
return {
validEdit: !length || isExp(val, /^[a-zA-Z0-9!#$%&'*+-/=?^_`{|}~."(),:;<>@[\]]+$/),
validFinal: length && isExp(val, COMMON_REGEX.email)
}
}
}
我希望输出取决于输入
const validity = getInputValidity(EMAIL_INPUT_DATA, emailVal )
所以如果EMAIL_INPUT_DATA.type==="email"
我希望有效性类型为
{
validEdit: boolean
validFinal: boolean
}
有可能吗?当前有效性键入为
const validity: true | {
readonly validEdit: boolean;
readonly validFinal: boolean | 0;
readonly validLength?: undefined;
readonly validChars?: undefined;
} | {
readonly validLength: boolean;
readonly validChars: boolean;
readonly validEdit?: undefined;
readonly validFinal?: undefined;
}
我知道可以通过将getInputValidity输入为函数来完成此操作,但是可以从实现中推断出来吗?
答案 0 :(得分:0)
您可以使用function overloads来做到这一点:
const isExp = (s: String, r: RegExp) => true;
interface IValidityReturn {
validEdit: boolean;
validFinal: boolean;
}
function getInputValidity(inputData: { type: 'select' }, val: string): boolean;
function getInputValidity(inputData: { type: 'select' }, val: string): boolean;
function getInputValidity(inputData: { type: 'select' | 'email' }, val: string): boolean | IValidityReturn {
const { length } = val
if (inputData.type==="select"){
return val.length<5
}
if (inputData.type==="email"){
return {
validEdit: !length || isExp(val, /^[a-zA-Z0-9!#$%&'*+-/=?^_`{|}~."(),:;<>@[\]]+$/),
validFinal: !!length && isExp(val, /a/g),
}
}
// only to make example work:
return {
validEdit: false,
validFinal: false,
}
}
出于示例的目的,将这些部分中的一部分拼凑在一起,但看来这应该可以解决问题。