请签名如下:

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

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


当前回答

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

这对我很管用。

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

其他回答

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

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

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

你可以在接口上指定多个方法签名,然后在类方法上重载多个方法:

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

class MyNotificationService implements INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
    error(message: string, autoHideAfter?: number);
    error(message: string, param1?: (string|number), param2?: number) {
        var autoHideAfter: number,
            title: string;

        // example of mapping the parameters
        if (param2 != null) {
            autoHideAfter = param2;
            title = <string> param1;
        }
        else if (param1 != null) {
            if (typeof param1 === "string") {
                title = param1;
            }
            else {
                autoHideAfter = param1;
            }
        }

        // use message, autoHideAfter, and title here
    }
}

现在所有这些都可以工作了:

var service: INotificationService = new MyNotificationService();
service.error("My message");
service.error("My message", 1000);
service.error("My message", "My title");
service.error("My message", "My title", 1000);

...INotificationService的error方法将有以下选项:

操场上

如文档中所述,使用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);

操场上的链接。

另一种方法是:

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];
};

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