Home > Enterprise >  Typescript enum, array as value
Typescript enum, array as value

Time:01-14

This looks odd to me

enum MessageStatusGroup {
  PENDING = [1, 2, 3],
  PUBLISHED = [4],
  DRAFT = [0],
}

and my linter gives error enter image description here

Is there any limitation in typescript that prevents specifing array as value?

CodePudding user response:

jna and TBA are right.

But may be you can simply workaround with :

export const MessageStatusGroup = {
  PENDING : [1, 2, 3],
  PUBLISHED : [4],
  DRAFT : [0],
} as const;

It should do the trick. The 'as const' at the end will ensure immutability of MessageStatusGroup, then it can be used the same way as an enum.

CodePudding user response:

Short answer is that TypeScript support numeric and string-based enums, array are not supported.

CodePudding user response:

Yes, in TypeScript enums, the values must be either string or number types. An array is not a valid value. This is why your linter is giving an error.

TypeScript provides both numeric and string-based enums.

Third line here

You can also point to other enums

enum Foo {
  Bar = 'Baz'
}

enum PointTo {
  Bar = Foo.Bar
}

And for numeric enums, you can also point to functions that return numeric values.

const numFunc = () => 4;

enum PointTo {
  Function = numFunc()
}

Check out typescriptlang for more examples

  • Related