Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Typescript中定义枚举类型的数组_Typescript - Fatal编程技术网

在Typescript中定义枚举类型的数组

在Typescript中定义枚举类型的数组,typescript,Typescript,我已经创建了一个Typescript DTO,在这里我希望确保字符串列表的类型安全(这些字符串是从枚举类型派生的) 导出类ConnectedUserWithPhotosDTO扩展UserWithPhotosDTO{ userTags:keyof User[“userTags”][] 构造函数(用户:用户,照片:ResponsePhotoDTO[]){ 超级(用户、照片) console.log(user.userTags) this.userTags=user.userTags; } } t

我已经创建了一个Typescript DTO,在这里我希望确保字符串列表的类型安全(这些字符串是从枚举类型派生的)


导出类ConnectedUserWithPhotosDTO扩展UserWithPhotosDTO{
userTags:keyof User[“userTags”][]
构造函数(用户:用户,照片:ResponsePhotoDTO[]){
超级(用户、照片)
console.log(user.userTags)
this.userTags=user.userTags;
}
}
typescript编译器抱怨以下错误:

类型“UserTags[]”不能分配给类型“number | keyof UserTags[]]”。

显然,
userTags
的值计算为

number | keyof UserTags[][]
这是我正在定义的枚举定义

导出枚举用户标记{
适合度=‘适合度’,
Fourtwo_FRIENDLY='420 FRIENDLY',
冥想=‘冥想’,
饮料=‘饮料’,
狗=‘狗’,
猫=‘猫’,
FASHION=‘FASHION’,
品酒=‘品酒’,
FOODIE=‘FOODIE’,
艺术=‘艺术’,
聚会=‘聚会’,
TRAVELIING=‘Traveling’,
博彩=‘博彩’,
}
在用户类中,
UserTags
定义为:

 @ApiProperty({ enum: UserTags, isArray: true, default: [] })
  @Column('enum', { enum: UserTags, array: true, nullable: true, default: [] })
  userTags: UserTags[]

如何为特定的枚举值定义
keyof
的类型?

假设UserTags是Enum

userTags: Array<keyof typeof UserTags>
userTags:Array

您还可以执行以下操作:


const userTags:User['userTags'];

您的帖子有点混乱,因为您使用了
keyof
。不清楚您想要的是枚举键
“FITNESS”
,还是枚举值
“FITNESS”
,等等

根据
用户
的代码和您的错误消息,很明显,当您访问
User.userTags
时,您得到的是值。值的类型只是枚举本身,因此您需要

userTags: UserTags[]
就像您在
User
中拥有的一样。这将与
User
中的类型相匹配,因为我们是基于
User[“userTags”]
设置
userTags
属性的


让我们分析一下您尝试的用户[“userTags”][的类型,看看它的真正含义

User[“userTags”]
为我们提供了
User
类型的
userTags
属性。我们可以从
User
代码中看到
User[“userTags”]
userTags[]
。这是
userTags
枚举中的值数组。类似于
[“Fitness”,“Fashion”]

User[“userTags”][]
意味着我们需要一个数组。但是它已经是一个数组了,所以您现在需要一个枚举值数组:
userTags[][]
。这将是
[[“Fitness”],[“Fashion”,“Foodie”]

keyof User[“userTags”][]
意味着我们现在需要该数组的键:
keyof userTags[][]
。数组的键是一个
数字
,所以typescript给你
数字| keyof userTags[][]
(我不确定为什么它不仅仅是
数字



可能您正试图获取
UserTags
enum对象的键?
keyof-typeof-UserTags
将为您提供联合类型
“FITNESS”|“FOURTWENTY\u-FRIENDLY”|“冥想”…
。但这似乎不是您实际想要使用的。您需要枚举值的并集,即
UserTags

提供
User
类型。不清楚您想做什么。我99%确定您只想要字符串enums,想要
UserTags:UserTags[]
,但我将在回答中解释问题是,
UserTags
是用户类上的一个嵌套属性。请提供用户类定义。您的答案是他们要求的-枚举对象的键。但我认为这不是他们真正想要的。他们显然很困惑,但我认为他们想要枚举值
数组
。编译器如何知道它是一个实例还是一个列表?@它只使用与
User
类型中的
userTags
属性完全相同的类型。