给出以下签名:
export interface INotificationService {
error(message: string, title?: string, autoHideAfter?: number);
}
如果不指定title
参数,但将autoHideAfter
设置为1000
,如何调用函数error()
发布于 2015-06-09 22:20:02
按照documentation中的指定,使用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);
发布于 2015-06-09 22:18:42
不幸的是,在TypeScript中没有这样的东西(更多细节在这里:https://github.com/Microsoft/TypeScript/issues/467)
但是为了解决这个问题,你可以把你的params改成一个接口:
export interface IErrorParams {
message: string;
title?: string;
autoHideAfter?: number;
}
export interface INotificationService {
error(params: IErrorParams);
}
//then to call it:
error({message: 'msg', autoHideAfter: 42});
发布于 2018-10-05 22:46:04
另一种方法是:
error(message: string, options?: {title?: string, autoHideAfter?: number});
因此,当您想要省略title参数时,只需像这样发送数据:
error('the message', { autoHideAfter: 1 })
我更喜欢这个选项,因为它允许我添加更多参数,而不必发送其他参数。
https://stackoverflow.com/questions/30734509
复制相似问题