如何声明一个只接受两个或零个参数的函数?

aab*_*leh 3 typescript

在 TypeScript 中,如果我声明一个这样的函数

function foo(arg1?: any, arg2?: any)
Run Code Online (Sandbox Code Playgroud)

那么如果我用以下命令调用该函数,编译器就不会抱怨

  • 零参数
  • 一个论点
  • 两个论点

如果我希望编译器遵守一个参数而不是两个或零个参数,我应该如何声明该函数?

Man*_*uel 7

您可以使用函数重载: https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads

// Start with most specific overload signature
function foo(arg1: any, arg2: any): any; 

// And then, less specific overload signature
function foo(): any; 

// At the end, write your function implementation
function foo(arg1?: any, arg2?: any) {
  console.log(arguments);
}

foo(1, 'test'); // Ok
foo(); // Ok 
foo('a'); // Compile error
Run Code Online (Sandbox Code Playgroud)