简体   繁体   English

Typescript 枚举,数组作为值

[英]Typescript enum, array as value

This looks odd to me这对我来说很奇怪

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

and my linter gives error我的 linter 出错了在此处输入图像描述

Is there any limitation in typescript that prevents specifing array as value? typescript 是否有任何限制阻止将数组指定为值?

jna and TBA are right. jna 和 TBA 是对的。

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.最后的 'as const' 将确保 MessageStatusGroup 的不变性,然后它可以像枚举一样使用。

Yes, in TypeScript enums, the values must be either string or number types.是的,在 TypeScript 枚举中,值必须是字符串或数字类型。 An array is not a valid value.数组不是有效值。 This is why your linter is giving an error.这就是为什么您的 linter 会出错。

TypeScript provides both numeric and string-based enums. TypeScript 提供基于数字和字符串的枚举。

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查看typescriptlang以获取更多示例

Short answer is that TypeScript support numeric and string-based enums, array are not supported.简短的回答是 TypeScript 支持数字和基于字符串的枚举,不支持数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM