MST

星途 面试题库

面试题:TypeScript泛型类与接口的协同设计

设计一个泛型类Cache,它接受一个键类型K和值类型V。这个类需要实现一个接口ICache,该接口包含get(key: K): V | undefined和set(key: K, value: V): void方法。此外,Cache类还需要有一个过期时间的功能,当通过get方法获取值时,如果值已过期(假设使用时间戳判断),则返回undefined。请给出完整的TypeScript代码实现。
22.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
interface ICache<K, V> {
    get(key: K): V | undefined;
    set(key: K, value: V): void;
}

class Cache<K, V> implements ICache<K, V> {
    private cache: Map<K, { value: V; expiration: number }> = new Map();

    constructor(private ttl: number) {}

    get(key: K): V | undefined {
        const entry = this.cache.get(key);
        if (entry && Date.now() < entry.expiration) {
            return entry.value;
        }
        this.cache.delete(key);
        return undefined;
    }

    set(key: K, value: V): void {
        const expiration = Date.now() + this.ttl;
        this.cache.set(key, { value, expiration });
    }
}