Home > Mobile >  Can I use array variable to define typescript?
Can I use array variable to define typescript?

Time:09-22

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 ...

CodePudding user response:

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)) {
  // ...
}

  • Related