带有查找对象的打字稿中的歧视类型工会
我有一些可能具有不同类型签名的事件接口,具体取决于它是什么类型的事件。假设我们有“ fizzchange”和“ buzzchange”,并且
interface EventTypeBase {
id: string;
timestamp: string;
}
interface FizzChange extends EventTypeBase {
name: 'fizz';
payload: string;
}
interface BuzzChange extends EventTypeBase {
name: 'buzz';
payload: number;
}
现在我们定义了它,它们都扩展了“ eventTypebase”,我们可以将其用于函数,并且有条件的语句检查我们正在尝试使用的是什么
const mapEventsWithIfs = (event: EventType) => {
// This works, typescript can see what type we want to use
if (event.name === 'fizz') {
return event.payload; // Typescript can see that this is a string
}
if (event.name === 'buzz') {
return event.payload; // And this is a number
}
return;
}
类型,是,我想使用一个查找对象,而每种类型都具有自己的处理程序功能,但这是不起作用的,而不是IF语句。如何以一种可以工作的方式键入查找对象?
const mapEvents = (event: EventType) => {
// This doesn't work, event gets reduces to never
// Argument of type 'EventType' is not assignable to parameter of type 'never'.
// The intersection 'FizzChange & BuzzChange' was reduced to 'never'
// because property 'name' has conflicting types in some constituents.
// Type 'FizzChange' is not assignable to type 'never'.(2345)
return EventHandlersMap[event.name](event);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Here's a somewhat involved approach that uses the 歧视联盟 映射类型href =“ https://stackoverflow.com/a/48751007/3558960”>在这里#generic-constraints“ rel =“ nofollow noreferrer”> generic约束:
游乐场链接
Here's a somewhat involved approach that uses the discriminated union mapped type approach described here along with a generic constraint:
Playground link
添加 Fizz 和 Buzz 作为类型。
在EvensHandLersMap中,将您的对象类型类型。因此,打字稿将了解对象。
Add fizz and buzz as type.
In EventHandlersMap give type to your object. So typescript will understand the object.