I am trying to get the number values of the enum IOSSubscriptionStatus
but when I try to cast my string to the enum and then use that enum to get the number value I get the followin error
Type 'string' is not assignable to type 'number'.
Here is the code. I put a comment behind the line that throws the error
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');
});
But when I test it in TSPlayground
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);
I get the expected output of 2
as expected so why don't I get a value of type number in my cloud functions? I am running the code in a cloud function with typescript 3.8.0
Why do You think that 2
is unexpected ? Please take a look how TS will convert your code to JS: Before - TS version
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);
After, JS version
"use strict";
var Test2;
(function (Test2) {
Test2[Test2["Yo"] = 4] = "Yo";
Test2[Test2["Do"] = 4] = "Do";
Test2[Test2["Mo"] = 2] = "Mo";
})(Test2 || (Test2 = {}));
const x = "Mo";
const test = x;
const conv = Test2[test];
console.log(conv);
So, Test2
is simple object
var Test2 = {2: "Mo", 4: "Do", Yo: 4, Do: 4, Mo: 2};
const x = "Mo";
const test = x;
const conv = Test2[test];// same as Test2["Mo"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.