Typescript 如何使用枚举中的实例从枚举中获取数值?
我正在尝试获取枚举的数值Typescript 如何使用枚举中的实例从枚举中获取数值?,typescript,enums,google-cloud-functions,Typescript,Enums,Google Cloud Functions,我正在尝试获取枚举的数值IOSSubscriptionStatus,但当我尝试将字符串强制转换到枚举,然后使用该枚举获取数值时,我得到以下错误 Type 'string' is not assignable to type 'number'. 这是代码。我在抛出错误的行后面放了一条注释 enum IOSSubscriptionStatus { 'CANCEL' = 3, 'DID_CHANGE_RENEWAL_PREF' = -1, 'DID_CHANGE_RENEWA
IOSSubscriptionStatus
,但当我尝试将字符串强制转换到枚举,然后使用该枚举获取数值时,我得到以下错误
Type 'string' is not assignable to type 'number'.
这是代码。我在抛出错误的行后面放了一条注释
enum IOSSubscriptionStatus {
'CANCEL' = 3,
'DID_CHANGE_RENEWAL_PREF' = -1,
'DID_CHANGE_RENEWAL_STATUS' = -1,
'DID_FAIL_TO_RENEW' = 6,
'DID_RECOVER' = 1,
'DID_RENEW' = 2,
'INITIAL_BUY' = 4,
'INTERACTIVE_RENEWAL' = 2,
'PRICE_INCREASE_CONSENT' = 8,
'REFUND' = 13,
'RENEWAL' = 2,
}
export const handleAppStoreServerNotification = functions.region('europe-west1').https.onRequest(async (req, res) => {
if (req.query.key !== developerNotificationKeys.key || req.body?.data == null)
return res.status(200).send('Recieved successfully');
const json = JSON.parse(req.body.data);
const notificationType = json['notification_type'] as unknown as IOSSubscriptionStatus;
if(notificationType === null || notificationType === undefined)
return res.status(200).send('Recieved successfully');
const notificationTypeId : number = IOSSubscriptionStatus[notificationType]; // This line throws the error
return res.status(200).send('Recieved successfully');
});
但当我在操场上测试的时候
enum Test2 {
"Yo" = 4,
"Do" = 4,
"Mo" = 2
}
const x :string = "Mo" ;
const test = x as unknown as Test2;
const conv : number = Test2[test]
console.log(conv);
我得到了
2
的预期输出,所以为什么我不能在我的云函数中得到一个number类型的值呢?我使用typescript 3.8.0
在云函数中运行代码,为什么您认为2
是意外的?
请看TS将如何将您的代码转换为JS:
Before-TS版本
enum Test2{
“Yo”=4,
“Do”=4,
“Mo”=2
}
常数x:string=“Mo”;
常数test=x与Test2一样未知;
const conv:number=Test2[test]
console.log(conv);
之后,JS版本
“严格使用”;
var测试2;
(函数(Test2){
Test2[Test2[“Yo”]=4]=“Yo”;
Test2[Test2[“Do”]=4]=“Do”;
Test2[Test2[“Mo”]=2]=“Mo”;
})(Test2 | |(Test2={}));
const x=“Mo”;
常数检验=x;
const conv=Test2[test];
console.log(conv);
所以,Test2
是一个简单的对象
var Test2={2:“Mo”,4:“Do”,Yo:4,Do:4,Mo:2};
const x=“Mo”;
常数检验=x;
const conv=Test2[test];//与Test2相同[“Mo”]
我认为2并不意外。抱歉,如果我用问号误导了您,但我不明白为什么const notificationTypeId:number=IOSSubscriptionStatus[notificationType];给定的错误类型“string”不可分配给类型“number”。您已创建简单字符串(x),然后尝试将其强制转换为对象。这是违法的