สร้างพร็อกซีไปยังฟังก์ชันที่มีการโอเวอร์โหลดหลายแบบใน TypeScript
ฉันมีปัญหากับโค้ดต่อไปนี้เมื่อพยายามสร้างพร็อกซีให้กับฟังก์ชันที่มีการโอเวอร์โหลดหลายแบบ:
// The function to proxy
function original (a: number): boolean;
function original (a: string): boolean;
function original (a: boolean): boolean;
function original (a: number | string | boolean): boolean {
return true;
}
// The proxy
function pass (a: string | number){
return original(a); // here
};
pass(5);
pass('a');
pass(true);
เมื่อพยายามสร้างพร็อกซีให้กับฟังก์ชัน original TypeScript ได้แสดงข้อผิดพลาดดังต่อไปนี้:
No overload matches this call.
Overload 1 of 3, '(a: number): boolean', gave the following error.
Argument of type 'string | number' is not assignable to parameter of type 'number'.
Type 'string' is not assignable to type 'number'.
Overload 2 of 3, '(a: string): boolean', gave the following error.
Argument of type 'string | number' is not assignable to parameter of type 'string'.
Type 'number' is not assignable to type 'string'.
Overload 3 of 3, '(a: boolean): boolean', gave the following error.
Argument of type 'string | number' is not assignable to parameter of type 'boolean'.
Type 'string' is not assignable to type 'boolean'.(2769)
input.tsx(5, 10): The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible.
มีสิ่งที่ควรรู้เกี่ยวกับเรื่องนี้ไม่กี่อย่าง:
- ฉันลดข้อบกพร่องของฉันลงไปในสถานการณ์ที่เล็กที่สุดซึ่งเกิดปัญหา
- การเรียกใช้
pass(true)ส่งผลให้เกิดข้อผิดพลาด ดังนั้นการพิมพ์จึงดูเหมือนว่าจะทำงานสำหรับฟังก์ชันpass - ในสถานการณ์ของฉัน ฟังก์ชัน
originalมาจากโมดูล ดังนั้นถ้ามีสถานการณ์ใดที่ไม่มีการแก้ไขมันจะเป็นเรื่องสมบูรณ์แบบ
นี่คือสนามเด็กเล่น TS พร้อมกับโค้ดก่อนหน้านี้
คำตอบ #1
ถ้าการกำจัดข้อผิดพลาดคือเป้าหมายของคุณ การตรวจสอบประเภทก่อนเรียกฟังก์ชันต้นฉบับจะช่วยกำจัดข้อผิดพลาดได้
function pass (a: string | number){
if (typeof a === "number") {
return original(a);
} else if(typeof a === "string"){
return original(a);
}
throw new Error(`Expected string or number`);
};
คำตอบ #2
แค่แปลงเป็นประเภทที่ต้องการ
function original(a: number): boolean;
function original(a: string): boolean;
function original(a: boolean): boolean;
function original(a: number | string | boolean): boolean {
return true;
}
const pass = original as (a: string | number) => boolean
pass(5);
pass('a');
pass(true);
https://www.typescriptlang.org/play?ssl=15&ssc=1&pln=1&pc=1#code/GYVwdgxgLglg9mABHATjA5jMBDANgCmwC5EwQBbAIwFMUBKEyuOXa7MAbgFgAoUSWAmRpMOAsUQBnKGjDoGiJizade-aPCSoMWPIUbNW7BUqOqea8BqHbReiWSq1EAHykys6V4sMqTv9kQAb15ERBRqKBAUJBkQam4eAF9eXggEaUQAB2xJSUQAXmEdMURcxH13WS83Rxp6QoA+H2V2VJ4cvPwAVjpEzsl8AHJsIb7eAfw46nGLHiA
