Can I use array variable to define typescript?

Let say I have a constant variable

const STATUS = {

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

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

Can I do something like

type status = Object.values(STATUS)


>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];

Leave a Reply