请签名如下:

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

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


当前回答

另一种方法是:

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

所以当你想要省略title参数时,就像这样发送数据:

error('the message', { autoHideAfter: 1 })

我宁愿这个选项,因为允许我添加更多的参数,而不必发送其他人。

你也可以在方法的签名中使用Partial<T>类型,但在这种情况下,你必须为你的选项创建一个接口:

interface IMyOptions {
  title: string;
  autoHideAfter: number;
}

然后这个方法的签名可以是这样的:

error(message: string, options?: Partial<IMyOptions>);

用法与上述相同。

Type Partial<T>应该已经在全局类型中声明如下:

type Partial<T> = {
  [P in keyof T]?: T[P];
};

其他回答

另一种方法是:

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

所以当你想要省略title参数时,就像这样发送数据:

error('the message', { autoHideAfter: 1 })

我宁愿这个选项,因为允许我添加更多的参数,而不必发送其他人。

你也可以在方法的签名中使用Partial<T>类型,但在这种情况下,你必须为你的选项创建一个接口:

interface IMyOptions {
  title: string;
  autoHideAfter: number;
}

然后这个方法的签名可以是这样的:

error(message: string, options?: Partial<IMyOptions>);

用法与上述相同。

Type Partial<T>应该已经在全局类型中声明如下:

type Partial<T> = {
  [P in keyof T]?: T[P];
};

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

这对我很管用。

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

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

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

在上述:

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

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

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

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

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

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