gpt4 book ai didi

typescript - 如何按序号访问 Typescript 枚举

转载 作者:搜寻专家 更新时间:2023-10-30 20:33:07 24 4
gpt4 key购买 nike

我有以下...

enum NubDirection {
OUTWARD,
INWARD
}
...
direction : NubDirection;
...
let index = Math.floor(Math.random() * 2) + 1;
nub.direction = NubDirection[index];

但这会抛出

error TS2322: Type 'string' is not assignable to type 'NubDirection'.

最佳答案

如果你有这样的字符串枚举:

export enum LookingForEnum {
Romantic = 'Romantic relationship',
Casual = 'Casual relationship',
Friends = 'Friends',
Fun = 'Fun things to do!'
}

然后

 const index: number = Object.keys(LookingForEnum).indexOf('Casual'); // 1

关于typescript - 如何按序号访问 Typescript 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39427542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com