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