使用带有默认初始化程序的重载函数

Use overloaded function with default initializer

您好,我正在尝试重载一个函数,该函数会更改 return 参数类型

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;
  }

我已经在选项参数上设置了默认初始化程序,如您所见,但是当我尝试调用该函数时出现错误

TS2554: Expected 3 arguments, but got 2. 

此外,即使我将选项设置为 false

,它也不会更改我的 return 类型并将其保持在 ValidationWithError 状态

我不确定你是怎么处理参数错误的。 TS2554: Expected 3 arguments, but got 2. 我无法用您的代码重现它。 但是如果您从第一个签名中删除?,TS 将正确推断出return 类型。这是有道理的,因为当 optionsundefined{ errors: false } 时,你想 return 一个 boolean 但你只 return 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