【问题标题】:How to correctly return from function如何正确从函数返回
【发布时间】:2022-01-18 11:40:33
【问题描述】:

在我的情况下,如何正确地将 apiKey 从 User.ts createUser 函数返回到 Test.ts?

用户.ts

interface User {
  url: string,
  name: string,

}
class User{
  async createUser(
   user: User
  ):Promise<void> { 
    let apiKey = await user.getUserApiKey(user.name);
    console.log(`${user.name} api key - ${apiKey} received`);
return apiKey;
    }
}

Test.ts

test("Smoke Test", async (t) => {
console.log(${apiKey} - User api key)
}

【问题讨论】:

    标签: javascript typescript testing types


    【解决方案1】:

    您可能必须将Promise&lt;void&gt; 指定为正确类型的apiKey。 它可能看起来像 Promise&lt;String&gt;,或者将返回类型规范留空(即从 createUser 方法中删除 : Promise&lt;void&gt;)。

    在 Test.ts 中你必须先创建一个 User 对象并在这个对象上调用createUser 方法。

    test("Smoke Test", async (t) => {
        let user = new User();
        user.name = "theName";
        user.url = "theURL";
        let apiKey = await user.createUser(user);
        console.log(${apiKey} - User api key)
    }
    

    看来,createUser 方法设计得不好。尽管在用户对象上调用它,但是否有意使用(可能不同)user 参数?

    【讨论】:

      猜你喜欢
      • 2011-10-29
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      • 2022-10-07
      • 2011-08-16
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多