I have an interface:
export interface Person {
firstName?: string;
lastName?: string;
status?: Status;
}
export enum Status {
Single,
Married,
Divorced
}
if I create a Person
Person john = {
firstName: "John",
lastName: "Smith",
status: Status.Married,
}
And I decide to access John's status by
var johnStatus = john.status;
I would get a number (1)
How do I make it so that I get the actual values (Single, Married, and Divorced) instead of a number? I am very new to typescript and it doesn't seem like there are a lot of info on this online. I tried adding keyword such as 'typeof' or 'keyof' but they don't work. Is there any other keywords I can use. Do I need to create a helper method? I will appreciate any help!
CodePudding user response:
export enum Status {
Single,
Married,
Divorced
}
//to string
const str1 = Status[Status.Single];
console.log(str1); // "Single"
// var johnStatus = Status[john.status];
or you can do
// STRING Enums
export enum Status {
Single = 'Single',
Married = 'Married',
Divorced = 'Divorced'
}
const str2 = Status.Single;
console.log(str2); //"Single"
// var johnStatus = john.status;