user1814879 user1814879 - 3 years ago 175
TypeScript Question

How to add an enum in model class in Typescript

I define a model class and I would like to add an enum label like :

export class User {
userID: number;
nom: string;
prenom: string;
dateCretation: Date;
statut: enum {
Value1,
Value2
};
}


I got a mark error in enum : [ts] Type expected.
How can I resolve it ?

Answer Source

You will need to declare the enum beforehand, and then type it to the properties that you want to have of that type:

export enum Values{
  Value1,
  Value2
}

export class User {
  userID: number;
  nom: string;
  prenom: string;
  dateCretation: Date;
  statut: Values
}

Another alternative is that if you know for sure that statut can only strictly take in two values, of which they are type of, say, string, then you can do like the following:

export class User {
  userID: number;
  nom: string;
  prenom: string;
  dateCretation: Date;
  statut: "Value1" | "Value2"
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download