ค้นหาเว็บไซต์

typescript - การโอเวอร์โหลดเมธอดไม่เฉพาะเจาะจงพอ


ฉันมีโค้ดนี้ :

declare class Demo<T extends { [key: string]: any }> {
    find<K extends keyof T>(key: K): Array<T[K]>;
    find(key: string): any
}

const demo1 = new Demo<{ foo: number }>();
const result1 = demo1.find('foo'); // correct (number[])
const result2 = demo1.find('fooo'); // correct (any)

const demo2 = new Demo();
const result3 = demo2.find('test'); // incorrect (any[]), should be any

สนามเด็กเล่น

ความคิดเห็นเหล่านี้อาจพูดได้ด้วยตัวมันเอง แต่โดยพื้นฐานแล้วผมต้องการให้การโอเวอร์โหลดที่สองได้รับการพิจารณาสำหรับการเรียก find ใด ๆ เมื่อไม่มีการส่งเจเนอริกไปยัง Demo น่าเศร้าที่ "test" ตรงตามข้อจำกัด keyof { [key: string]: any } ดังนั้นการโอเวอร์โหลดแรกจึงถูกเรียก ผมสามารถแก้ปัญหานี้ได้อย่างไร ? ขอบคุณครับ

คำตอบ #1

ถ้าไม่เป็นปัญหาที่จะทำให้คลาสกว้างขึ้นเล็กน้อย คุณสามารถจำกัด T ให้เป็น object แทน {[key: string]: any} เพื่อหลีกเลี่ยงปัญหาเกี่ยวกับดัชนี การเพิ่ม & string ในข้อจำกัดของ find ครั้งแรกจะป้องกันไม่ให้มันเข้ากับคีย์ที่ไม่ใช่สตริง:

declare class Demo<T extends object> {
    find<K extends keyof T & string>(key: K): Array<T[K]>;
    find(key: string): any
}

const demo1 = new Demo<{ foo: number }>();
const result1 = demo1.find('foo'); // correct (number[])
const result2 = demo1.find('fooo'); // correct (any)

const demo2 = new Demo();
const result3 = demo2.find('test'); // correct (any)

สนามเด็กเล่น TypeScript