【发布时间】:2021-02-14 03:50:09
【问题描述】:
我正在尝试在 Typescript 类型方面做得更好,并且需要类型安全的事件发射器。我现在尝试了许多不同的方法,但我似乎无法正确解决类型。你能看出我哪里出错了吗?
在下面的示例中,我有一个“事件”类型,它将事件名称映射到必须与该事件一起传递的参数。因此,如果我发出“Foo”,我还必须传递一个“bar”字符串,并且侦听器应该知道有一个“bar”属性要读取。
interface Events {
Foo: {
bar: string;
}
}
type EventKeys = keyof Events
class Emitter {
...
emit<K extends EventKeys> (title: K, value: Events[K]): void {
// With this signature I want to require if the caller specifies a title of "Foo"
// then they must specify value as "{bar: string}". This part looks to work great!
this.emitter.emit("connection", [title, value])
}
public on (listener: any): void {
// I use "any" here because this part of the code isn't super relevant to this example
this.emitter.on('connection', listener.event.bind(f))
}
}
class Listener {
...
event<K extends EventKeys> ([title, value]: [title: K, value: Events[K]]): void {
switch(title) {
case "Foo":
console.log(value)
// Here "value" is of type "Events[K]",
// which I take to mean it should know it's type "Events[Foo]"
// or actually "{bar: string}",
// but I don't get the autocompletion I expect.
break
}
}
}
不可能从Events[K]这样的泛型中获取{bar: string}吗?
【问题讨论】:
标签: typescript generics