请签名如下:

export interface INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
}

我如何调用函数error()不指定标题参数,但设置autoHideAfter说1000?


当前回答

你可以使用可选变量by ?或者如果你有多个可选变量。,例如:

function details(name: string, country="CA", address?: string, ...hobbies: string) {
    // ...
}

在上述:

必须填写姓名 Country是必选项,有默认值 地址可选 嗜好是一个可选参数数组

其他回答

您可以在没有接口的情况下做到这一点。

class myClass{
  public error(message: string, title?: string, autoHideAfter? : number){
    //....
  }
}

使用?运算符作为可选参数。

如文档中所述,使用undefined:

export interface INotificationService {
    error(message: string, title?: string, autoHideAfter? : number);
}

class X {
    error(message: string, title?: string, autoHideAfter?: number) {
        console.log(message, title, autoHideAfter);
    }
}

new X().error("hi there", undefined, 1000);

操场上的链接。

https://www.typescriptlang.org/docs/handbook/functions.html

在JavaScript中,每个参数都是可选的,用户可以根据自己的需要去掉它们。当它们这样做时,它们的值是未定义的。我们可以在TypeScript中通过添加?我们希望参数的末尾都是可选的。例如,我们希望上面的last name参数是可选的:

function buildName(firstName: string, lastName?: string) {
  if (lastName) return firstName + " " + lastName;
  else return firstName;
}
 
let result1 = buildName("Bob"); // works correctly now
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
Expected 1-2 arguments, but got 3.
let result3 = buildName("Bob", "Adams"); // ah, just right

在这种情况下,你可以对那些你不想覆盖的可选参数使用“undefined”值

export interface INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
}

你可以调用类似的错误方法

error("it works", undefined, 20);

注意,null在这里不起作用。

你可以使用可选变量by ?或者如果你有多个可选变量。,例如:

function details(name: string, country="CA", address?: string, ...hobbies: string) {
    // ...
}

在上述:

必须填写姓名 Country是必选项,有默认值 地址可选 嗜好是一个可选参数数组