0

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!

1 Answer 1

1
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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.