请签名如下:
export interface INotificationService {
error(message: string, title?: string, autoHideAfter?: number);
}
我如何调用函数error()不指定标题参数,但设置autoHideAfter说1000?
请签名如下:
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];
};
其他回答
您可以创建一个helper方法,该方法根据错误参数接受一个对象参数
error(message: string, title?: string, autoHideAfter?: number){}
getError(args: { message: string, title?: string, autoHideAfter?: number }) {
return error(args.message, args.title, args.autoHideAfter);
}
不幸的是,TypeScript中没有这样的东西(更多细节请访问:https://github.com/Microsoft/TypeScript/issues/467)
但是为了解决这个问题,你可以把你的参数改成一个接口:
export interface IErrorParams {
message: string;
title?: string;
autoHideAfter?: number;
}
export interface INotificationService {
error(params: IErrorParams);
}
//then to call it:
error({message: 'msg', autoHideAfter: 42});
您可以尝试将title设置为null。
这对我很管用。
error('This is the ',null,1000)
在这种情况下,你可以对那些你不想覆盖的可选参数使用“undefined”值
export interface INotificationService {
error(message: string, title?: string, autoHideAfter?: number);
}
你可以调用类似的错误方法
error("it works", undefined, 20);
注意,null在这里不起作用。
如文档中所述,使用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);
操场上的链接。