【发布时间】: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