lodash - การแปลงประเภท Typescript เมื่อทำการแตกโครงสร้าง
สมมติว่านี่
{foo, bar} = groupBy(arg);
ฉันต้องการแปลง foo เป็นชนิด Foo และ bar เป็นชนิด Bar ทำได้อย่างไร?
ฉันเป็นมือใหม่แบบสมบูรณ์กับ Typescript groupBy เป็นฟังก์ชันจากแพ็กเกจ lodash
คำตอบ #1
ถ้า Typescript ไม่สามารถสรุปชนิดของผลลัพธ์จาก groupBy ได้ คุณสามารถลองกำหนดเองได้
function groupBy(o: any) {
return o; // return any
}
let x = { a: 1, b: "1" }
// we know better than tsc and assert the type
let {a, b} = <{ a: number, b: string }>groupBy(x);
