嗨,我正在嘗試多載一個更改引數回傳型別的函式
isValidPropertyValue(propertyName: string, value: any,
options?: { errors: true }): ValidationWithErrors;
isValidPropertyValue(propertyName: string, value: any,
options?: { errors: false }): boolean
isValidPropertyValue(propertyName: string, value: any,
options = { errors: false }): boolean | ValidationWithErrors {
if (typeOf(propertyName) !== "string") throw new Error("propertyName must be a string");
const conditions = this.properties[propertyName];
if (!conditions) {
return options.errors ? {
valid: false,
errors: [{
property: propertyName,
error: `Unauthorized property '${propertyName}'`
}]
} : false;
}
const errors: PropertyError[] = [];
for (const [condition, validator] of Object.entries(propertyValidators)) {
if (conditions[condition]) {
try {
validator(conditions[condition], value);
} catch (e: any) {
errors.push({ property: propertyName, error: e.message });
}
}
}
return options.errors ? { valid: !errors.length, errors } : !errors.length;
}
我已經在 option 引數上設定了一個默認初始化程式,就像您看到的那樣,但是當我嘗試呼叫該函式時出現錯誤
TS2554: Expected 3 arguments, but got 2.
此外,即使我將選項設定為 false,它也不會更改我的回傳型別并將其保持在 ValidationWithError 上
uj5u.com熱心網友回復:
我不確定你是怎么去論證錯誤的。TS2554: Expected 3 arguments, but got 2.我無法用你的代碼重現它。但是如果您?從第一個簽名中洗掉,TS 將正確推斷回傳型別。這是有道理的,因為當options是undefinedor時{ errors: false },您想回傳 aboolean但您只ValidationErrors在它是時回傳,{ errors: true }而不是在它未定義時回傳。
interface ValidationWithErrors {
valid: boolean;
errors: { property: string; error: string }[];
}
function isValidPropertyValue(
propertyName: string,
value: any,
options: { errors: true }
): ValidationWithErrors;
function isValidPropertyValue(
propertyName: string,
value: any,
options?: { errors: false }
): boolean;
function isValidPropertyValue(
propertyName: string,
value: any,
options = { errors: false }
): boolean | ValidationWithErrors {
if (options.errors) {
return {
valid: false,
errors: [{ property: propertyName, error: 'invalid value' }],
};
}
return false;
}
const isValid = isValidPropertyValue('property', 'value'); // boolean
const validationWithErrors = isValidPropertyValue('property', 'value', {
errors: true,
}); // ValidationWithErrors
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438962.html
