从 Typescript 中的属性值推断对象的类型

v-累了

我在 Typescript 中有以下代码(简化)

interface TimeoutOption {
  category: 'timeout'
  time: number
}

interface UserOption {
  category: Parameters<typeof addEventListener>[0]
}

type MyDelayOptions = Array<TimeoutOption | UserOption>


function delay(options: MyDelayOptions) {
  for (const option of options) {
    if (option.category === 'timeout') {
      timeout = setTimeout(() => {
        // not relevant
      }, option.time) // need to cast and do (option as TimeoutOption) to not get an error
    }
  }
}


为了避免编译错误,我必须添加注释中提到的类型断言。对于人类来说,很明显 if the categoryis 'timeout'my optionis of type TimeoutOption如果没有类型断言,我怎样才能使这项工作?欢迎完整的重构。

TJ克劳德

问题是UserOption定义category为类型string(间接地,但这就是它的结果)。这样一来,if (option.category === 'timeout')就不会歧视你的两个工会成员,因为UserOption很容易就可以category: "timeout"做到TimeoutOption判别式 ( category) 必须明确区分工会,但在您的情况下并非如此。

您可以测试是否存在time(见***下文):

function delay(options: MyDelayOptions) {
  for (const option of options) {
    if ("time" in option) { // ***
      const timeout = setTimeout(() => {
        // not relevant
      }, option.time) // need to cast and do (option as TimeoutOption) to not get an error
    }
  }
}

游乐场链接

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章