Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I use array variable to define typescript?

Let say I have a constant variable

const STATUS = {
    ACTIVE: "ACTIVE",
    DELETED: "DELETED",
  }

And I have a function which input is status

const handleStatus = (status) {
//do some thing
}

I want to define interface for status just accept ‘ACTIVE’ and ‘DELETED’ so I have to manually define like bellow

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type status = 'ACTIVE' | 'DELETED'
const handleStatus = (status : status) {
//do some thing
}

Can I do something like

type status = Object.values(STATUS)

Thanks!

>Solution :

There’re 2 options for you. As a suggestion in comment to switch using enum in this case, another way is to use keyof keyword in terms of still wanting to have a string literal as type:

type Status = keyof typeof STATUS;

PS: If you prefer the values as type rather than the keys, you need to tweak a bit more:

const STATUS = {...} as const // mark it as constant

type Status = (typeof STATUS)[keyof typeof STATUS];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading