请签名如下:

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

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


当前回答

您可以尝试将title设置为null。

这对我很管用。

error('This is the ',null,1000)

其他回答

您可以创建一个helper方法,该方法根据错误参数接受一个对象参数

 error(message: string, title?: string, autoHideAfter?: number){}

 getError(args: { message: string, title?: string, autoHideAfter?: number }) {
    return error(args.message, args.title, args.autoHideAfter);
 }

您可以尝试将title设置为null。

这对我很管用。

error('This is the ',null,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

在TS中,您还可以将参数设置为Object,并使对象的值可选,这样您就不必定义每个参数,只需定义您想要使用的参数即可。

公共函数beingcalled (obj:{状态?: number,错误?:字符串,消息?:字符串}){ If (obj.message) {console.log(obj.message)} } 这一点。functionBeingCalled({消息:'检测到错误'})

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

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

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