MST

星途 面试题库

面试题:TypeScript泛型类继承与约束

编写一个泛型类`SortedCollection`,它继承自一个基础泛型类`Collection`。`Collection`类有一个用于添加元素的`add`方法。`SortedCollection`类需要确保添加的元素是有序的(假设元素类型实现了比较方法),请合理使用泛型约束来实现这一功能,并给出完整的TypeScript代码。
17.7万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
class Collection<T> {
    protected items: T[] = [];
    add(item: T) {
        this.items.push(item);
    }
}

class SortedCollection<T extends Comparable<T>> extends Collection<T> {
    add(item: T) {
        let inserted = false;
        for (let i = 0; i < this.items.length; i++) {
            if (item.compareTo(this.items[i]) < 0) {
                this.items.splice(i, 0, item);
                inserted = true;
                break;
            }
        }
        if (!inserted) {
            this.items.push(item);
        }
    }
}

interface Comparable<T> {
    compareTo(other: T): number;
}