【问题标题】:TypeError: Parameter must be a string, not objectTypeError:参数必须是字符串,而不是对象
【发布时间】:2019-07-07 20:54:12
【问题描述】:

我试图让一个函数返回一个字符串,但它所做的只是返回一个对象。我也不能使用.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”必须是字符串,而不是对象

【问题讨论】:

  • Promise&lt;string&gt; 不是string 类型。您需要等待 Promise 解决,或者使 setServerURL 不是异步的(因为它似乎没有做任何异步工作)。
  • 我是量角器的新手,不知道该怎么做。我猜删除异步会导致代码不同步。没有承诺解决我如何得到错误 - TypeError: Parameter "url" must be a string, not object
  • 现在,您可以将您的代码更改为serverURL: string = 'https://abcqwer.com';,完全删除setServerURL,并看不出有什么区别。您可能想edit您的问题,以展示该功能中实际发生的情况,也许我们可以为您提供更好的建议。

标签: typescript protractor


【解决方案1】:

此方法this.setServerURL(this.currentEnvironment) 返回Promise&lt;string&gt; 而不是string。但是为什么你需要setServerURL() 成为async?如果你不做任何承诺交互,你可以重写它:

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

假设您需要做一些promise 的事情,而您的setServerURL() 返回Promise&lt;string&gt;

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

【讨论】:

  • 谢谢。有用。我删除了异步,它工作正常。我对异步等待方法相对较新,因此对 setServerURL 的异步没有太多理由。再次感谢。
猜你喜欢
  • 2018-05-16
  • 2019-06-27
  • 2023-02-18
  • 2017-01-28
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多