[英]Use overloaded function with default initializer
Hi I'm trying to overload a function that change return type on parameter嗨,我正在尝试重载一个改变参数返回类型的 function
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;
}
I have set a default initializer on the option parameter like you can see but when I'm trying to call the function I got an error我已经在选项参数上设置了默认初始化程序,就像您看到的那样,但是当我尝试调用 function 时出现错误
TS2554: Expected 3 arguments, but got 2.
Futhermore it doesn't change my return type and keep it on ValidationWithError even if I set the option to false此外,即使我将选项设置为 false,它也不会更改我的返回类型并将其保留在 ValidationWithError 上
I'm not sure how you go the argument error.我不确定你 go 参数错误是怎么回事。
TS2554: Expected 3 arguments, but got 2.
I wasn't able to reproduce that with your code. TS2554: Expected 3 arguments, but got 2.
我无法用您的代码重现它。 But if you remove the ?
但是如果你删除了
?
from the first signature , TS will correctly infer the return type.从第一个签名,TS 将正确推断返回类型。 It makes sense because when
options
is undefined
or { errors: false }
, you want to return a boolean
but you only return ValidationErrors
when it's { errors: true }
and not when it's undefined.这是有道理的,因为当
options
undefined
或{ errors: false }
时,您想返回一个boolean
但您只在{ errors: true }
而不是未定义时返回ValidationErrors
。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.