Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an enum in class in Typescript

Tags:

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 ?

like image 877
user1814879 Avatar asked Jul 27 '17 07:07

user1814879


People also ask

Can we define enum inside a class TypeScript?

Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too. In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.

Can I declare enum inside a class?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

Can I use enum as a type in TypeScript?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

Can I use TypeScript enum in JavaScript?

Enums are a feature added to JavaScript in TypeScript which makes it easier to handle named sets of constants. By default an enum is number based, starting at zero, and each option is assigned an increment by one. This is useful when the value is not important.


1 Answers

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"
}
like image 134
CozyAzure Avatar answered Oct 19 '22 23:10

CozyAzure