簡體   English   中英

使用帶有默認初始化程序的重載 function

[英]Use overloaded function with default initializer

嗨,我正在嘗試重載一個改變參數返回類型的 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;
  }

我已經在選項參數上設置了默認初始化程序,就像您看到的那樣,但是當我嘗試調用 function 時出現錯誤

TS2554: Expected 3 arguments, but got 2. 

此外,即使我將選項設置為 false,它也不會更改我的返回類型並將其保留在 ValidationWithError 上

我不確定你 go 參數錯誤是怎么回事。 TS2554: Expected 3 arguments, but got 2.我無法用您的代碼重現它。 但是如果你刪除了? 從第一個簽名,TS 將正確推斷返回類型。 這是有道理的,因為當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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM