TypeError:参数必须是字符串,而不是对象

时间:2019-02-13 21:58:10

标签: typescript protractor

我试图使一个函数返回一个字符串,但它所做的只是返回一个对象。我也不能使用.toString()方法。

currentEnvironment: string = "beta";
serverURL: string = this.setServerURL(this.currentEnvironment);
URL: string = this.serverURL;

async setServerURL(env: string): Promise<string> {
  const myText: string = 'https://abcqwer.com';
  return myText;
}


async login(): Promise<void> {
  console.log('Login URL is: ' + this.URL.toString());
  await browser.get(this.URL);
};

我收到此错误:

  

TypeError:参数“ url”必须是字符串,而不是对象

1 个答案:

答案 0 :(得分:1)

此方法this.setServerURL(this.currentEnvironment)返回Promise<string>而不是string。但是,为什么需要setServerURL()才能成为async?如果您不进行任何承诺交互,则可以将其重写:

setServerURL(env: string): string {
  const myText: string = 'https://abcqwer.com';
  return myText;
}

想象一下,您需要做一些promise的事情,而您的setServerURL()返回Promise<string>

currentEnvironment = "beta"; // here typescript understand that variable has string type
serverURL: Promise<string> = this.setServerURL(this.currentEnvironment);
URL: Promise<string> = this.serverURL;

async setServerURL(env: string): Promise<string> {
  const myText: string = 'https://abcqwer.com';
  return myText; // even if 'myText' is string this method will return Promise<string> because it method has async keyword
}


async login(): Promise<void> {
  const url = await this.URL;
  console.log('Login URL is: ' + url);
  await browser.get(url);
};