ฉันกำลังมองหาคำตอบที่สามารถหาได้enum
จาก a string
แต่ในกรณีของฉันค่า enums มีค่าสตริงที่ต่างกัน OP มี enum ง่ายสำหรับColor
แต่ฉันมีสิ่งที่แตกต่าง:
enum Gender {
Male = 'Male',
Female = 'Female',
Other = 'Other',
CantTell = "Can't tell"
}
เมื่อคุณพยายามที่จะแก้ไขGender.CantTell
ด้วย"Can't tell"
สตริงมันจะกลับมาundefined
พร้อมกับคำตอบเดิม
คำตอบอื่น
โดยพื้นฐานแล้วฉันมากับคำตอบอื่นที่ได้แรงบันดาลใจจากคำตอบนี้ :
export const stringToEnumValue = <ET, T>(enumObj: ET, str: string): T =>
(enumObj as any)[Object.keys(enumObj).filter(k => (enumObj as any)[k] === str)[0]];
หมายเหตุ
- เรารับผลลัพธ์แรกของ
filter
สมมติว่าไคลเอนต์กำลังส่งสตริงที่ถูกต้องจาก enum หากไม่ใช่กรณีดังกล่าวundefined
จะถูกส่งคืน
- เราได้เหวี่ยง
enumObj
ไปany
เพราะมี typescript 3.0 ขึ้นไป (ปัจจุบันใช้ typescript 3.5) ที่ได้รับการแก้ไขenumObj
unknown
ตัวอย่างการใช้งาน
const cantTellStr = "Can't tell";
const cantTellEnumValue = stringToEnumValue<typeof Gender, Gender>(Gender, cantTellStr);
console.log(cantTellEnumValue); // Can't tell
หมายเหตุ: noImplicitAny
และเป็นคนชี้ให้เห็นในความคิดเห็นผมยังอยากจะใช้
อัปเดตเวอร์ชันแล้ว
ไม่มีany
การคัดลอกและพิมพ์ที่เหมาะสม
export const stringToEnumValue = <T, K extends keyof T>(enumObj: T, value: string): T[keyof T] | undefined =>
enumObj[Object.keys(enumObj).filter((k) => enumObj[k as K].toString() === value)[0] as keyof typeof enumObj];
นอกจากนี้เวอร์ชันที่อัปเดตมีวิธีที่ง่ายกว่าในการโทรหาและอ่านได้ง่ายขึ้น:
stringToEnumValue(Gender, "Can't tell");
--noImplicitAny
(ใน VS ไม่ได้เลือก "อนุญาตประเภท" ใด ๆ "โดยนัย) มันผลิตerror TS7017: Index signature of object type implicitly has an 'any' type.
สำหรับฉันนี้ทำงาน:var color: Color = (<any>Color)[green];
(ทดสอบกับรุ่น 1.4)