【问题标题】:Union types and iterating over an array联合类型和遍历数组
【发布时间】:2020-08-20 07:53:48
【问题描述】:

我有一个这样的界面:

interface foo {a: "first", b: "second"}

我正在使用如下函数推断类型:

const myFunc = <P extends keyof foo>(prop: P, value:SomeObject[P]) => {
return console.log(P +":" + value)
}

然后我这样做:

Object.keys({a: "something", b: "somethingelse"}).map((x, id) => {
 myFunc(a, "randomtext")
})

我收到一个错误: 'string' 类型的参数不能分配给 '"a" 类型的参数 | "b"'。

为什么会这样?

【问题讨论】:

  • console.log(P +":" + value) - 当P 是一种类型时,这是没有意义的,因为它在运行时不存在。
  • 感谢@kaya3,同意。

标签: typescript typing


【解决方案1】:

Object.keys 的返回类型始终为 string[],无论传递给它的参数如何

【讨论】:

  • 好吧,知道了。谢谢。您将如何解决上述情况?
  • if (x === "a" | x === "b") myFunc(x, "randomtext") else // do error handling
  • 好的,谢谢。这感觉就像不必要地增加了代码。我可以采取其他方法来避免这种情况吗?
猜你喜欢
  • 2019-11-14
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 2013-06-13
  • 1970-01-01
  • 2021-11-14
  • 2012-06-26
相关资源
最近更新 更多