Typescript 函数重载不起作用

问题描述 投票:0回答:1

错误是

Type '(str: string, convert?: unknown) => { result: number; } | { result: string; }' is not assignable to type 'X'.
  Type '{ result: number; } | { result: string; }' is not assignable to type '{ result: string; }'.
    Type '{ result: number; }' is not assignable to type '{ result: string; }'.
      Types of property 'result' are incompatible.
        Type 'number' is not assignable to type 'string'.
interface X {
    (str: string): {
        result: string
    }
    (str: string, convert: true): {
        result: number
    }
}

const func: X = (str, convert = false) => {
    if (convert) return {
        result: parseInt(str, 10)
    }

    return {
        result: str
    }
}

游乐场

typescript function overloading
1个回答
0
投票

请查看函数重载的文档。

function x(str: string): string;
function x(str: string, convert=true): number;
function x(str: string, convert?: boolean) {
  if (convert) {
    return parseInt(str, 10);
  }

  return str;
}
© www.soinside.com 2019 - 2024. All rights reserved.