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

เจนเนอริก - ฉันจะตรวจสอบได้อย่างไรว่า element เป็น instance ของ U?


ฉันต้องการเพิ่มองค์ประกอบประเภท any ลงในอาเรย์และภายหลังดึงองค์ประกอบจากอาเรย์นี้ที่เป็นตัวเลข:

function OfType<T, U>(list: T[]) : U[]
{
    var result: U[] = [];

    list.forEach(e => {
        // I want to check if e is of type U
        //if (typeof(e) === typeof(U)) // ERROR: doesn't work
            result.push(<U><any>e);
    });

    return <any[]>result;
}


var list: any[] = [];
list.push("A");
list.push(2);

var result = OfType<any, number>(list);

alert(result.toString());

แต่มันไม่อนุญาตให้ฉันตรวจสอบประเภทขององค์ประกอบกับประเภททั่วไปได้

มีวิธีใดในการทำให้สำเร็จไหม?

คำตอบ #1

คุณสามารถทำมันได้ดีขึ้นมากในตอนนี้ด้วยวิธีนี้ (TypeScript 3.9):

// tslint:disable-next-line: no-any
type Constructor<T> = new (...args: any[]) => T;

export function ofType<TElements, TFilter extends TElements>(
    array: TElements[], 
    filterType: Constructor<TFilter>
): TFilter[] {
    return <TFilter[]>array.filter(e => e instanceof filterType);
}

ตัวอย่างการใช้งาน:

class ClassA { }
class ClassB { }

const list: ClassA[] = [new ClassA(), new ClassB()];
const filteredList = ofType(list,  ClassB);

บทความที่เกี่ยวข้อง