【问题标题】:How to write a conditional promise.resolve properly in typescript?如何在打字稿中正确编写有条件的 promise.resolve?
【发布时间】:2021-07-05 06:55:16
【问题描述】:

我有一个使用 typescript 进行原生反应的项目,我想使用 Promise.resolve().then() 的对象,其条件会导致 typescript 出现类型错误。以下是情况:

我有第一个对象(作为样本):

const objectA = async () => {
  // get the object from local storage
  const user = await asyncStorage.getItem(userAKey)

  return {
    // types are all in string
    id: user?.id || '',
    email: user?.email || '',
  }
}

我有我的第二个对象(作为示例):

const objectB = async () => {
  // get the object from local storage
  const user = await asyncStorage.getItem(userBKey)

  return {
    // types are all in string
    id: user?.id || '',
    email: user?.email || '',
    organisation: user?.organisation || ''
  }
}

所以这两个对象都有不同的类型和具有值的键。这就是问题所在,我有一个条件是根据某种主机类型检查要解析的对象:

const objectTobeResolved = type === 'primary' ? objectA : objectB

因此,基于该条件,我将其传递给 Promise:

const userData = () => {
   Promise.resolve(objectTobeResolved).then((values) => { ... })
}

我会在objectTobeResolved 的打字稿中看到类型错误。 基本上这里的类型错误提到了objectA | objectB之类的东西,但我实际上只需要根据上述条件传递一个对象,我不需要objectA | objectB条件,因为它只是objectA或@ 987654331@ 基于我在应用启动器中声明的主机类型。

由于我刚刚学会使用 Typescript,我不太明白如何在 typescript 中正确声明它。

在这里写承诺的正确方法是什么?我应该改用race 还是all?但我一次只需要检查一个对象。或者我应该以某种方式声明或初始化?或者我什至根本不需要使用promise

编辑:我已将上面的代码更新为我的真实案例。 代码实际上运行正确,只是类型错误不断出现,我无法通过测试。一个捷径是使用 //@ts-ignore,但由于我们的做法是不忽略警告,所以我试图找到一种正确的方法来编写它,而不会出现导致测试失败的警告。

【问题讨论】:

  • 看起来你的类型提示是错误的。你能把它定义的行也贴出来吗?
  • 首先,您应该真正考虑为什么要这样做。除非您有非常特殊的需要,否则Promise.resolve(value).then((value) => {}) 相当于直接使用value。其次,由于您编写的代码在 TS 中可以正常工作并完美编译,因此我们看不到代码中应该发生了其他事情
  • 这是一个不错的问题,但我们确实需要完整的代码示例。
  • 请在minimal reproducible example 上发布完整代码。目前尚不清楚在哪里评估条件以及在哪里定义调用then 的函数。
  • objectAobjectB 都是承诺返回函数,所以会期望像 (type === 'primary' ? objectA() : objectB()).then(values => ...) 这样的东西。

标签: javascript typescript react-native async-await promise


【解决方案1】:

更多代码会有所帮助,但我认为您可能要问的是如何创建联合类型,以便您可以有效地将结果引用为 this 或 that。如果是这样,也许你可以使用这样的东西?我相信你也可以用其他一些方式来表达它,但我只是想说明这一点。

const objectA = {
    a: 1,
    b: 2,
}

const objectB = {
    c: 3,
    d: 4,
    e: 5,
}

interface ABtype {
    a: Number
    b: Number
}

interface CDEtype {
    c: Number
    d: Number
    e: Number
}

interface ABpromiseType extends Promise<ABtype> {
}

interface CDEpromiseType extends Promise<CDEtype> {
}

interface ABCDEunionTypeCombined extends Promise<CDEtype | ABtype> {
}

// Something randomly true or false.
let conditionalCheck = new Date().getTime() % 2 == 0;

const someFunction = () => {
    const objectTobeResolved : ABCDEunionTypeCombined  = (conditionalCheck ? Promise.resolve(objectA) : Promise.resolve(objectB) );
}

【讨论】:

    猜你喜欢
    • 2019-04-27
    • 1970-01-01
    • 2019-10-07
    • 2022-11-15
    • 2021-01-29
    • 1970-01-01
    • 2023-02-06
    • 2016-06-10
    • 2021-12-21
    相关资源
    最近更新 更多