1

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

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

Can I do something like

type status = Object.values(STATUS)

Thanks!

Edit : I define type status = (typeof STATUS)[keyof typeof STATUS] But when I try to check if status is valid

const validStatus = Object.values(STATUS)
if(!validStatus.includes(status)) {
  //do something
}

Typescript throw error

Argument of type 'string' is not assignable to parameter of type ...
1
  • 2
    You probably want an enum. Commented Sep 22, 2022 at 4:26

1 Answer 1

2

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

Answer for newly added request

Looks like misunderstand between typing vs its value. You can't set a type as value which means you have to create a variable with the type you already defined (Don't define a type name as lowercase status) so here's the example:

type Status = (typeof STATUS)[keyof typeof STATUS];

// this is the value which needs to create with your created type
const status: Status = 'ACTIVE';

// you can set this type as: `Status[]` or 
// you don't need to do so cause
// tsc can infer correct type as `Status[]`
const validStatus = Object.values(STATUS);

if(!validStatus.includes(status)) {
  // ...
}

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @tmhao2005 I have another problem with this. Could you check my edit. Thanks
I just added the additional explanation and code snippet for you :)

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.