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 ?
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.
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
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.
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.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With