พารามิเตอร์เจเนอริกของฟังก์ชัน TypeScript ในอาร์กิวเมนต์แบบกระจาย
ฉันมีฟังก์ชันดังต่อไปนี้:
type SomeType<T> = Record<string, T>;
declare function test<T>(...args: SomeType<T>[]): T;
ฉันอยากจะเรียกมันแบบนั้น (a ควรเป็นชนิด number|string):
const a = test({a: 3}, {b: "as"});
แต่แบบนั้นฉันจะได้ข้อผิดพลาด: Type 'string' is not assignable to type 'number'. ฉันสามารถทำให้มันใช้งานได้โดยไม่ต้องส่งอาร์กิวเมนต์เจนริกรูปแบบ number|string อย่างชัดเจนหรือไม่ หรือไม่ต้องใช้ชนิดเงื่อนไข?
สนามเด็กเล่น
คำตอบ #1
ทูเพิลแบบแปรผันอาจช่วยได้:
declare function test<T extends any[]>(...args: [...T]): T;
const a = test({ a: 3 }, { b: "as" });
