简体   繁体   English

Typescript:接口获取属性的默认值

[英]Typescript: interface gets default value for property

I am writing an event system with different types of events in angular 11我正在编写一个包含不同类型事件的事件系统 angular 11
I am defining an enum for the different types of events我正在为不同类型的事件定义一个枚举

enum EventTypes {
  Pending,
  Active,
  Complete
}

and interfaces for the different events和不同事件的接口

interface PendingEvent { type: EventTypes.Pending }

interface ActiveEvent { type: EventTypes.Active, progress: number }

interface CompleteEvent { type: EventTypes.Complete, data: any }

I then define a type to bundle those events然后我定义一个类型来捆绑这些事件

type Event = PendingEvent | ActiveEvent | CompleteEvent;

But now, every time i create a new event i have to give a type.但是现在,每次我创建一个新事件时,我都必须给出一个类型。

const event: ActiveEvent = {
  progress: 83
}

I get an error saying that i am missing the 'type' property.我收到一条错误消息,提示我缺少“类型”属性。
I expect the type to be automatically set depending on the event type i create.我希望根据我创建的事件类型自动设置类型。

If you use classes you might be able to achieve what you want.如果您使用类,您可能能够实现您想要的。 You can even keep the interface if you like, or simplify it to one interface.如果您愿意,您甚至可以保留该界面,或将其简化为一个界面。

interface EventInterface { type: EventTypes; progress?: number; data?: any}
class ActiveEvent implements EventInterface {
   constructor (progress: number) {
     this.type =  EventTypes.Active;
     this.progress = progress;
     }
}
const event = new ActiveEvent(82);

Similarly you can make classes for the other two types of Events, which constructors automatically set the type.同样,您可以为其他两种类型的事件创建类,构造函数会自动设置类型。

Of course, classes and instances of classes aren't the same as typed variables as you have now, but it sounded like this might help your (guessed by me) use case.当然,类和类的实例与您现在所拥有的类型变量不同,但听起来这可能会帮助您(我猜到)用例。

Information here may be helpful: https://www.typescriptlang.org/docs/handbook/interfaces.html#implementing-an-interface此处的信息可能会有所帮助: https://www.typescriptlang.org/docs/handbook/interfaces.html#implementing-an-interface

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM