ฉันกำลังมองหาคำตอบที่สามารถหาได้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) ที่ได้รับการแก้ไขenumObjunknown
ตัวอย่างการใช้งาน
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)